防止重新渲染在包装器组件中启动 useState 的同级组件

申格尔迪

我对 React 不是很有经验,但我有一个非常简单的设置。

export default function App() {
  const [title, setTitle] = useState("still-empty");

  const myFunction = title => {
    setTitle(title);
  };

  return (
    <div className="App">
      <ComponentA myFunction={myFunction} />
      <br />
      <br />
      <ComponentB title={title} />
    </div>
  );
}



const ComponentA = ({ myFunction }) => {
  console.log("Rendering Component A");

  return (
    <div onClick={() => myFunction(Math.random() * 1000)}> Component A </div>
  );
};

export default ComponentA;


const ComponentB = ({ title }) => {
  return <div> Title : {title}</div>;
};

export default ComponentB;

这是一个测试这个的沙箱:https : //codesandbox.io/s/musing-cookies-g7szr

请注意,如果您单击“ComponentA”,则确切的 ComponentA 会重新渲染(您可以在控制台中看到它),尽管此组件上没有更改任何道具。这是我真实用例的简化示例。在我的实际用例中,ComponentA 是一张地图,其中许多内容(缩放、中心)将被重置。我想防止这些重置以及重新渲染所需的 1 秒。因此,我提出了这个简化的例子。

那么如何将信息从 ComponentA 传递到 ComponentB,而不重新渲染 ComponentA 本身呢?感谢您在这里提供帮助。

粤港澳大湾区

useCallback在 Parent 中使用,这样函数就不会一次又一次地创建,而只会在初始渲染时创建。使用React.memo以便在没有更改道具时组件不会重新渲染。

应用程序

export default function App() {
  const [title, setTitle] = useState("still-empty");

  const myFunction = useCallback(title => {
    setTitle(title);
  }, []);

  return (
    <div className="App">
      <ComponentA myFunction={myFunction} />
      <br />
      <br />
      <ComponentB title={title} />
    </div>
  );
}

化合物

import React, { memo } from "react";

const ComponentA = ({ myFunction }) => {
  console.log("Rendering Component A");

  return (
    <div onClick={() => myFunction(Math.random() * 1000)}> Component A </div>
  );
};

export default memo(ComponentA);

工作演示在这里:https : //codesandbox.io/s/affectate-boyd-v7g2t?file=/src/App.js

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章