javascript – ComponentDidCatch不起作用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – ComponentDidCatch不起作用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1821字,纯文字阅读大概需要3分钟。
内容图文
![javascript – ComponentDidCatch不起作用](/upload/InfoBanner/zyjiaocheng/698/83cdfc30e241427ea956afa23a49efc3.jpg)
为什么componentDidCatch在我的react-native应用程序中不起作用.
componentDidCatch不处理错误.
React native v: 50.3
React: 16.0.0
import React, {Component} from 'react';
import {View, Text} from 'react-native';
import Logo from './SignUpInit/Logo';
import SignUp from './SignUpInit/SignUp';
import Social from './SignUpInit/Social';
import styles from './SignUpInit/styles';
export default class SignUpInit extends Component {
state = {
componentCrashed: false,
count: 0,
}
componentDidCatch(error, info) {
console.log(error);
console.log(info);
console.log('_______DID CATCH____________');
this.setState({componentCrashed: true});
}
componentDidMount(){
setInterval(()=>this.setState({count: this.state.count+1}),1000);
}
render() {
if (this.state.componentCrashed) {
return (
<View>
<Text>
Error in component "SingUpInit"
</Text>
</View>
);
}
if(this.state.count > 5){
throw new Error('Error error error');
}
return (
<View style={styles.main}>
<Logo/>
<SignUp/>
<Social/>
</View>
);
}
}
解决方法:
这不起作用,因为componentDidCatch()仅用于捕获组件子项抛出的错误.在这里,您似乎正在尝试捕获由同一组件抛出的错误 – 这不会起作用.
有关详细信息,请参阅official documentation:
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
请注意“子组件树中的任何位置”.
因此,您需要做的就是将组件包装在另一个管理所有错误的组件中.就像是:
<ErrorBoundary>
<SignUpInit />
</ErrorBoundary>
其中< ErrorBoundary />就像这样简单:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {hasError: false};
}
componentDidCatch(error, info) {
this.setState({hasError: true});
}
render() {
if(this.state.hasError) return <div>Error!</div>;
return this.props.children;
}
}
内容总结
以上是互联网集市为您收集整理的javascript – ComponentDidCatch不起作用全部内容,希望文章能够帮你解决javascript – ComponentDidCatch不起作用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。