为什么即使 state/dependency 已更改,应用程序也不会重新呈现
Why is the app not re-rendering even if the state/dependency has changed
我正在改变网格如下
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 函数时,网格正在更新但应用程序没有重新呈现?为什么会这样?
您正在改变旧数组而不是创建新数组。由于它们是引用相等的,因此反应会脱离渲染。由于数组是数组的数组,因此您还需要映射这些数组,并复制发生变化的节点。
const clearPath = () => {
const newGrid = grid.map((row) => {
return row.map((node) => {
if (node.isVisited) {
return { ...node, isVisited: false };
}
return node;
});
});
setGrid(newGrid);
};
我正在改变网格如下
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 函数时,网格正在更新但应用程序没有重新呈现?为什么会这样?
您正在改变旧数组而不是创建新数组。由于它们是引用相等的,因此反应会脱离渲染。由于数组是数组的数组,因此您还需要映射这些数组,并复制发生变化的节点。
const clearPath = () => {
const newGrid = grid.map((row) => {
return row.map((node) => {
if (node.isVisited) {
return { ...node, isVisited: false };
}
return node;
});
});
setGrid(newGrid);
};