首页 > 解决方案 > React,避免重新渲染特定的子组件

问题描述

我有这个组件树:

Father
    Son
        Childrens
    Daughter
        Childrens2
    Modal

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

我尝试的是使用

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

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

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

标签: reactjs

解决方案


  1. 在您shouldComponentUpdate的情况下,当两者都相同时,您将返回 true,因此它会更新。所以应该是

    shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean {
    
        return this.state.openSimpleModal != nextState.openSimpleModal
    }
    
  2. 如果不会导致任何性能问题,则无需关心重新渲染。
  3. 您可以根据您的要求使用 React.memo、React.PureComponent 或 React.useMemo

推荐阅读