为什么 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()
仅适用于捕获组件子项抛出的错误。在这里,您似乎正在 try catch 同一组件抛出的错误 - 这是行不通的。
参见 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 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47223765/