【问题标题】:Why is the (memoized) child component re-rendering?为什么(记忆的)子组件要重新渲染?
【发布时间】:2021-11-16 23:27:20
【问题描述】:

我有两个 React 功能组件:C1C2C2 嵌套在 C1 中:

const C2 = () => {
  console.log("C2 Render");
  return (
    <div>I am Component 2</div>
  );
};

const C1 = () => {
  const [text, setText] = useState("Hello");
  const MC2 = React.memo(C2, () => true);
  
  return (
    <div className="box">
      <h1>The Button</h1>  
      <button
        onClick={() => {
          setText(`${text} b`);
        }}
        className="button">
          Click me
       </button>
      <div>
        {text}
      </div>
      <MC2 />
    </div>
  );
}

CodePen here.

问题

我知道组件会在不同的情况下重新渲染。其中之一是父级重新渲染。

这就是我在C2 周围使用记忆组件的原因。但是每次单击按钮时,我仍然可以看到控制台显示"C2 Render"

为什么?

【问题讨论】:

    标签: javascript reactjs react-functional-component react-memo


    【解决方案1】:

    C1 因为状态改变而重新渲染,所以你的记忆组件每次都被重新声明。 只需将 C2 包装在 React.memo() 中,您就不会看到重新渲染

    const MC2 = React.memo(() => {
      console.log("C2 Render");
      return (
        <div>I am Component 2</div>
      );
    }, () => true);
    

    或者如果您只想记忆一个用例,请将其放在 C1 组件之外并记忆该组件:

    const C2 = () => {
      console.log("C2 Render");
      return (
        <div>I am Component 2</div>
      );
    };
    
    const MC2 = React.memo(C2, () => true);
    

    &这样使用它:

    const C1 = () => {
      const [text, setText] = useState("Hello");
      
      return (
        <div className="box">
          <h1>The Button</h1>  
          <button
            onClick={() => {
              setText(`${text} b`);
            }}
            className="button">
              Click me
           </button>
          <div>
            {text}
          </div>
          <MC2 />
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-12
      • 2021-12-04
      • 2020-08-14
      • 2020-06-16
      • 1970-01-01
      • 2018-08-12
      • 2019-06-01
      • 2020-02-13
      • 1970-01-01
      相关资源
      最近更新 更多