【问题标题】:React smooth rerender, replace contentReact 平滑重新渲染,替换内容
【发布时间】:2023-01-12 23:25:51
【问题描述】:

我的组件有一个从数据数组映射的项目列表。当数组发生变化时,整个组件(这个页面)消失并重新渲染,看起来很难看。

如果项目数没有改变,我该如何做出反应代替项目内容而不是重新安装我的组件?因此,分页很糟糕。

我的示例组件:


const Row = ({ text }) => {
  return <div>{text}</div>;
};

const Main = () => {
  const firstArray = [
    "firstText",
    "firstText",
    "firstText",
    "firstText",
    "firstText",
  ];
  const secondArray = [
    "secondText",
    "secondText",
    "secondText",
    "secondText",
    "secondText",
  ];
  const [page, setPage] = useState(firstArray);
  setTimeout(() => {
    setPage((prevState) => secondArray);
  }, 5000);
  return (

    <div>
      {page.map((e) => {
        return <Row text={e} />;
      })}
    </div>
  );
};



我尝试以不同的方式向我的服务器发出请求,但问题出在我的渲染上

【问题讨论】:

  • 因为您在映射时不使用任何keys
  • 此外,setTimeout 必须在 useEffect 中设置(并在 useEffect 清理函数中清除)

标签: reactjs react-hooks


【解决方案1】:

正如其他人在 cmets 中提到的那样,您需要 React 的密钥才能识别哪些列表项已更改并需要重新呈现。 Read more about lists and keys here

您可能还会发现了解 React 中的 reconciliationwhy keys are required 很有帮助。

在旁注中,请将您的setTimeout移至useEffect并在卸载时清除它以防止任何内存泄漏:

useEffect(() => {
  const timoutId = setTimeout(() => {
    setPage((prevState) => secondArray);
  }, 5000);

  return () => clearTimeout(timoutId);
}, []);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多