我是reactjs的初学者,并试图理解概念,例如父母和孩子在reactjs中的渲染方式以及渲染方式
从研究中我发现,反应首先使孩子然后是父母,但是我无法获得有效的答案,为什么以及为什么?以及如果子代无法渲染会发生什么,我想在反应16中有一个名为componentDidCatch的生命周期,该生命周期处理子代无法渲染的情况,因此反应16之前发生了什么以及我们如何处理这些情况
请帮我
当componentDidMount
火灾,你可以做DOM操作,因此是有道理的,家长只接收其子女被安装之后。也就是说,您可以使用componentWillMount
向相反方向开火,首先是父母。
如果很清楚,这就是在React 16.x中包装错误捕获的方法:
React 16.x错误处理示例
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
参考:https : //reactjs.org/blog/2017/07/26/error-handling-in-react-16.html
REACT 15错误处理示例
unstable_handleError()
是所有组件的函数,在render或child渲染错误时调用。
unstable_handleError: function(){
this.setState({error: "oops"})
}
class Boundary extends React.Component {
...
unstable_handleError() {
logErrorSoYouCanFixTheThing()
this.setState({error: true});
}
render() {
if (this.state.error){
return <SafeComponent/>
} else {
return <ComponentWithErrors/>
}
}
}
挂载时没有错误,因此呈现<ComponentWithErrors/>
。
假设<ComponentWithErrors/>
抛出错误,unstable_handleError()
将调用此组件,状态将更新为error: true
。
状态更新时,将<SafeComponent/>
呈现!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句