做出反应,避免重新渲染特定的子组件

时间:2019-12-13 00:02:27

标签: reactjs

我有这个组件树:

Father
    Son
        Childrens
    Daughter
        Childrens2
    Modal

每次Modal打开(通过设置this.setState({ openSimpleModal: true });)或关闭Modal(将状态设置为false)时,都会将组件Son,Daughter及其子组件重新渲染到。有没有一种方法可以打开和关闭Modal,但不允许重新渲染1个特定组件,例如Son(及其子代),而又重新渲染其余部分? (女儿等),但仅当模态打开或关闭时。我需要在其他情况下渲染每个子组件,但是当Modal打开/关闭时,我需要停止重新渲染

我尝试使用的是

shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean {

    return this.state.openSimpleModal === nextState.openSimpleModal
}

并确定模态的状态是否已更改,并且在这种情况下返回false,但它不起作用,因为模态当然不会显示。

2 个答案:

答案 0 :(得分:1)

在渲染从设备中,具有相同布尔状态的ChildComponent吗?

class Father {

 render() {

  return (
    <div>
    {this.state.openSimpleModal &&  <ChildComponent />}
    <MyModal show={openSimpleModal} />
    </div>
  );
 }
}

答案 1 :(得分:1)

  1. 在您的shouldComponentUpdate中,当两个都为 一样,所以它更新。所以应该是

    shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean {
    
        return this.state.openSimpleModal != nextState.openSimpleModal
    }
    
  2. 如果没有引起任何性能问题,则无需担心转售。
  3. 您可以根据需要使用React.memo,React.PureComponent或React.useMemo