开发者问题收集

更新对象数组中的值状态

2021-12-13
41

状态:

const [tiles, setTiles] = useState(tilesData)

状态内的数据:(tilesData)

const defaultValueCard = {
   name: 'Bahamut',
   cardValues: { N: 0, E: 0, S: 0, W: 0 },
   image: 'URL'
}

export const tilesData =
   [
      { tileNumber: 1, card: defaultValueCard },
      { tileNumber: 2, card: defaultValueCard },
      { tileNumber: 3, card: defaultValueCard },
      { tileNumber: 4, card: defaultValueCard },
      { tileNumber: 5, card: defaultValueCard },
      { tileNumber: 6, card: defaultValueCard },
      { tileNumber: 7, card: defaultValueCard },
      { tileNumber: 8, card: defaultValueCard },
      { tileNumber: 9, card: defaultValueCard },
      { tileNumber: 10, card: defaultValueCard },
      { tileNumber: 11, card: defaultValueCard },
      { tileNumber: 12, card: defaultValueCard },
      { tileNumber: 13, card: defaultValueCard },
      { tileNumber: 14, card: defaultValueCard },
      { tileNumber: 15, card: defaultValueCard },
      { tileNumber: 16, card: defaultValueCard }
   ]

updateTile 函数接收一个 tileIndex(编号在 1-16 之间)和一个包含与 defaultValueCard 相同数据的新卡片。

我如何在此函数内更新状态以在特定索引处用新卡片替换旧卡片?

const updateTile = (tileIndex, card) => {
 /* take the tileIndex and update the current card with the parameter card */
}
1个回答

尝试一下...

const [tiles, setTiles] = useState(tilesData);

const updateTile = (tileIndex, card) => {
 /* take the tileIndex and update the current card with the parameter card */
 const tilesCopy = [...tiles];
 const oldTileIndex = tilesCopy.findIndex(tile => tile.tileNumber === tileIndex);
 // a word of caution, oldTileIndex is undefined if tile with tileIndex DNE
 tilesCopy[oldTileIndex] = {tileNumber: tileIndex, card};
 setTiles(tilesCopy);
 
}
Gaurav
2021-12-13