【发布时间】:2019-07-11 20:23:52
【问题描述】:
我试图根据React16 Doc 实现一个 ErrorBoundary HoC 组件以进行错误处理。我将 ErrorBoundary 组件设为 PureComponent,我注意到 children 道具总是相等的,它试图防止重新渲染子组件。
class ErrorBoundary extends React.PureComponent {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return <PageNotFound />;
}
return this.props.children;
} }
将组件修改为 React.Component 并添加 componentDidUpdate 后,我可以看到 children 的 props 总是相等的。
componentWillUpdate(nextProps, nextState, nextContext) {
if(this.props.children === nextProps.children){ //returns TRUE
console.log('children value are equal')
}
}
下面的代码展示了我是如何使用 ErrorBoundary 组件的
<BrowserRouter>
<ErrorBoundary>
<Route path='/' component={Router} />
</ErrorBoundary>
</BrowserRouter>
谁能解释一下 children 道具是如何相等的?
【问题讨论】:
-
不确定您的问题。
ErrorBoundary在提供的代码中总是有相同的孩子,即Route?
标签: javascript reactjs react-router