【问题标题】:React How to re render map function on change of variabel?React如何在变量更改时重新渲染地图功能?
【发布时间】:2021-02-07 19:50:14
【问题描述】:

Here 是一段应该显示我的问题的摘录。在我的项目中,我对网格做了一些事情,现在我想重置它,但我不知道它是如何工作的,因为如果我更改网格变量,.map() 函数不会重新渲染。我希望你能理解我的问题并帮助我。

这是我的代码:

  export default function App() {
  const getInitialGrid = () => {
    const grid = [];
    for (let row = 0; row < 20; row++) {
      const currentRow = [];
      for (let col = 0; col < 50; col++) {
        currentRow.push([]);
      }
      grid.push(currentRow);
    }
    return grid;
  };
  const grid = getInitialGrid();
  return (
    <div className="App">
      {grid.map(function (row, rowIdx) {
        return (
          <div className="grid-row" key={rowIdx}>
            {row.map(function (node, colIdx) {
              return <div className="node">hi</div>;
            })}
          </div>
        );
      })}
    </div>
  );
}

Its the same code like here.

非常感谢!

【问题讨论】:

  • React 组件仅在 state 或 props 更新(或其父级重新渲染)时重新渲染,该组件既没有 state 也没有 props,因此它只会在其父级重新渲染时重新渲染。您能否更新您的问题以包括尝试重置任何内容或更新网格?
  • 不确定,但您可以在组件挂载时移动 getInitialGrid,在卸载时将其移除 useEffect(() =&gt; { setState(getInitialGrid()); return () =&gt; setState(); }, []),将其设置为新状态 const [state, setState] = useState();。

标签: javascript reactjs


【解决方案1】:

您应该为此使用useState 钩子。

import React, { useState } from 'react';

export default function App() {
    // App code
    const [grid, setGrid] = useState(getInitialGrid());
    // more App code

然后,如果您想为网格分配一个新值并导致重新渲染,您可以这样做(在您的 App 组件中):

setGrid(yourNewGrid);

【讨论】:

    猜你喜欢
    • 2022-12-23
    • 1970-01-01
    • 2021-01-14
    • 2019-08-09
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2022-01-17
    相关资源
    最近更新 更多