我正在如下更改网格
const clearPath = () => {
grid.map((row) => {
row.map((node) => {
if (node.isVisited) {
//console.log(node);
node.isVisited = false;
}
});
});
setGrid(grid);
console.log(grid);
};
并按如下所示渲染它
return (
<div className="arena">
{grid.map((row, i) => (
<div key={i} className="row">
{row.map((node, j) => {
const { row, col, isStart, isEnd, isWall, isVisited } = node;
return (
<Node
key={j}
col={col}
row={row}
node={node}
isEnd={isEnd}
isStart={isStart}
isWall={isWall}
isVisited={isVisited}
mouseIsPressed={mouseIsPressed}
onMouseDown={(row, col) => {
handleMouseDown(row, col);
}}
onMouseEnter={(row, col) => {
handleMouseEnter(row, col);
}}
onMouseUp={() => handleMouseUp()}
></Node>
);
})}
</div>
))}
</div>
);
但是当我调用clearPath函数时,网格正在更新,但是应用程序没有重新呈现吗?为什么会这样?
答案 0 :(得分:2)
您要更改旧数组,而不是创建新数组。由于它们是参考相等的,因此react会退出渲染。由于数组是数组的数组,因此您还需要映射它们,并制作更改的节点的副本。
const clearPath = () => {
const newGrid = grid.map((row) => {
return row.map((node) => {
if (node.isVisited) {
return { ...node, isVisited: false };
}
return node;
});
});
setGrid(newGrid);
};