【问题标题】:React, avoid re-rendering specific children componentReact,避免重新渲染特定的子组件
【发布时间】:2019-12-13 00:02:27
【问题描述】:

我有这个组件树:

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,但它不起作用,因为模态当然不会显示。

【问题讨论】:

  • 这取决于你如何渲染你的组件;你能展示更多你的模态组件吗?例如,当openSimpleModalfalse 时,如果它没有返回任何元素,则无法不重新渲染,因为它必须重新创建元素。
  • 我的理解是,我们的openSimpleModal设置为false,Father将被卸载,因此其他组件也将被卸载?如果它被卸载,它们都必须重新渲染。如果您关心的是保留状态,则应将状态存储在父组件中。如果您关心的是性能,则需要考虑其他因素来优化渲染。

标签: reactjs


【解决方案1】:

在渲染 slave 中具有相同布尔状态的 ChildComponent?

class Father {

 render() {

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

【讨论】:

    【解决方案2】:
    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

    【讨论】:

    • 1、但是状态只有在Modal被触发的时候才会发生变化,Father组件在很多情况下都会重新渲染,但是只有当modal的状态发生变化的时候才是我不想的时候让父亲渲染。 2,重新渲染弄乱了一个依赖于父亲组件道具的小组件,但只有在那种情况下,我不想再次从父亲 -> 儿子 -> SmallComponent 传递道具。 3,谢谢,我昨天读到了,我会检查更多
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2020-05-04
    • 2020-12-13
    • 1970-01-01
    • 2018-12-21
    • 2023-01-28
    相关资源
    最近更新 更多