【问题标题】:React Hook doesn't re-render array.map after state changeReact Hook 不会在状态更改后重新渲染 array.map
【发布时间】:2022-01-13 18:44:29
【问题描述】:

今天我试图通过遍历数组来渲染一些 reactHooks。

我现在遇到的问题是在 tileMap 状态更新时不会发生的重新渲染。

tileMap 是一个对象数组(参见文章结尾)

状态发生变化,我可以用正确的值记录它,但仍然没有渲染 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
}[][]>

【问题讨论】:

  • 您的问题不清楚。尝试添加完整代码。

标签: reactjs typescript react-hooks render


【解决方案1】:

你没有从tileMap.map 返回任何东西。添加一个退货,你应该会看到一些东西。

tileMap.map((row) => {
  return row.map((tile) => {
    return <Tile isLife={tile.isAlive}/>
  })
})

【讨论】:

    【解决方案2】:

    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 变量的值,所以我把它和索引一起加入了,但你可以放任何东西,只要它保持唯一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2021-09-09
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多