渲染许多元素时 React 很慢

Dir*_*ber 4 javascript reactjs

组件Cell的状态alive可以是truefalse

如果alive,则Cell呈现为div带有类的a alive(想想康威的生命游戏)。状态alive每秒更新一次:

function Cell(props) {
  const [alive, setAlive] = useState(
    Math.random() < props.aliveProbability / 100
  );

  useEffect(() => {
    const interval = setInterval(
      () => setAlive(Math.random() < props.aliveProbability / 100),
      1000
    );
    return () => clearInterval(interval);
  }, []);

  return (
    <div className={"cell " + (alive ? "alive" : "")}>{props.children}</div>
  );
}
Run Code Online (Sandbox Code Playgroud)

对于单个单元来说,这工作得很好。但是,当向网格添加多个单元组件时,渲染速度会减慢,并且是按顺序而不是同时进行。细胞越多,速度就越慢。如何解决这个问题?

可以在这里看到一个工作演示

Emi*_*ron 6

它慢的原因是因为每个单元格在稍微不同的时间自行触发新的渲染,因为每个setInterval回调都是单独调用的。

\n

不要为每个单元格设置一个间隔,而是将状态提升到父组件,执行一个间隔并更新整个数据集,然后使用结果数据渲染实际树一次。React 将负责优化 DOM 更改!

\n

这是一个使用单个单元数组的简化示例。

\n
// Simple "dumb" cell component\nfunction Cell({ alive, children }) {\n  return <div className={"cell " + (alive ? "alive" : "")}>{children}</div>;\n}\n\n// The app manages the update cycle\nfunction App() {\n  // Initial dataset\n  const [cells, setCells] = useState([\n    { alive: true, aliveProbability: 0.9 },\n    { alive: true, aliveProbability: 0.9 },\n    { alive: true, aliveProbability: 0.9 },\n  ]);\n\n  useEffect(() => {\n    const interval = setInterval(\n      () =>\n        setCells((cells) =>\n          // update the whole dataset once every interval\n          cells.map(({ aliveProbability }) => ({\n            alive: Math.random() < aliveProbability / 100,\n            aliveProbability,\n          }))\n        ),\n      1000\n    );\n    return () => clearInterval(interval);\n  }, []);\n\n  // Render the whole dataset once.\n  return <div>{cells.map(cellProps => <Cell {...cellProps} />)}</div>;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

现在,每秒只有一次更新和渲染,而不是数千次单独渲染。

\n

就像在游戏引擎中一样,现在只有一个游戏循环,而不是数千个游戏循环!

\n
\n

如果您想深入研究使用 React 进行游戏开发,那么已经有很好的例子了:

\n\n