React Hook 在状态更改后不会重新呈现 array.map
React Hook doesn't re-render array.map after state change
今天我试图通过遍历数组来渲染一些 reactHooks。
我现在遇到的问题是在 tileMap
状态更新时没有发生重新渲染。
tileMap
是对象数组的数组(参见 post 的末尾)
状态改变,我可以用正确的值记录它,但仍然没有渲染 Tile 组件
function resetGame() {
console.log("yo");
let tileMap = []
//tileMap is updated here
//This is always reached
setTileMap(tileMap)
}
<div className="life2dgame-root">
{
tileMap ?
tileMap.map((row) => {
row.map((tile) => {
console.log(tile);
return <Tile isLife={tile.isAlive}/>
})
})
:
null
}
</div>
tileMap 状态的类型
<{
loc: {height: number, width: number},
element: JSX.Element,
isAlive: boolean
}[][]>
React 使用 key 来决定重新渲染哪些元素;因为你没有在你的 map 函数中设置键,React 不会更新任何东西。尝试:
tileMap ?
tileMap.map((row, index) => {
row.map((tile) => {
console.log(tile);
return <Tile key={`${row + index}} isLife={tile.isAlive}/>
})
})
:
null
编辑:
你可以在键中放任何你想要的东西,我不知道你的 row
变量的值,所以我把它和索引结合起来了,但你可以放任何东西,只要它保持唯一。
您没有 return 从 tileMap.map
获取任何内容。添加一个 return,你应该会看到一些东西。
tileMap.map((row) => {
return row.map((tile) => {
return <Tile isLife={tile.isAlive}/>
})
})
今天我试图通过遍历数组来渲染一些 reactHooks。
我现在遇到的问题是在 tileMap
状态更新时没有发生重新渲染。
tileMap
是对象数组的数组(参见 post 的末尾)
状态改变,我可以用正确的值记录它,但仍然没有渲染 Tile 组件
function resetGame() {
console.log("yo");
let tileMap = []
//tileMap is updated here
//This is always reached
setTileMap(tileMap)
}
<div className="life2dgame-root">
{
tileMap ?
tileMap.map((row) => {
row.map((tile) => {
console.log(tile);
return <Tile isLife={tile.isAlive}/>
})
})
:
null
}
</div>
tileMap 状态的类型
<{
loc: {height: number, width: number},
element: JSX.Element,
isAlive: boolean
}[][]>
React 使用 key 来决定重新渲染哪些元素;因为你没有在你的 map 函数中设置键,React 不会更新任何东西。尝试:
tileMap ?
tileMap.map((row, index) => {
row.map((tile) => {
console.log(tile);
return <Tile key={`${row + index}} isLife={tile.isAlive}/>
})
})
:
null
编辑:
你可以在键中放任何你想要的东西,我不知道你的 row
变量的值,所以我把它和索引结合起来了,但你可以放任何东西,只要它保持唯一。
您没有 return 从 tileMap.map
获取任何内容。添加一个 return,你应该会看到一些东西。
tileMap.map((row) => {
return row.map((tile) => {
return <Tile isLife={tile.isAlive}/>
})
})