【问题标题】:React children props are always equalReact 儿童道具总是平等的
【发布时间】: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


【解决方案1】:

children 始终指代作为子组件传递的值,即&lt;Route&gt; React 元素:

<ErrorBoundary>
    <Route path='/' component={Router} />
</ErrorBoundary>

由于父组件没有重新渲染,&lt;Route&gt; 对象是相同的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多