React切换待添加游戏时如何保证已添加的游戏记录不被修改
问题根因
- 你将
GamesParent子组件定义在了App组件内部,且子组件直接引用了外层作用域的当前选中游戏变量game,没有使用已添加的游戏数据作为props传入。只要App组件重渲染,所有已渲染的GamesParent都会同步显示当前选中的游戏,导致旧的添加记录被修改。 - 调用添加逻辑时仅往state中存入了游戏名称字符串,后续遍历渲染时无法获取游戏id作为key,也无法对应完整的游戏属性。
修复后的可运行代码
import { useState } from 'react'; import { games as gamesJson } from './games.json'; // 子组件移到App外部定义,通过props接收对应游戏数据,避免受全局选中状态影响 const GamesParent = ({ game }: { game: { id: number; game: string; color: string } }) => { return ( <div style={{ color: game.color }}> <div>{game.game}</div> </div> ); }; const App: React.FC = () => { const [whichGameIsVar, setWhichGameIsVar] = useState(0); // 存储完整游戏对象而非仅名称 const [addedGames, setAddedGames] = useState<typeof gamesJson>([]); const selectedGame = gamesJson[whichGameIsVar]; function addGame() { setAddedGames([...addedGames, selectedGame]); } function chooseGameToAdd() { // 增加边界判断,避免索引超出游戏列表长度报错 setWhichGameIsVar(prev => (prev + 1) % gamesJson.length); } return ( <div> {addedGames.map((item) => ( <GamesParent key={item.id} game={item} /> ))} <button onClick={addGame}>添加游戏</button> <button onClick={chooseGameToAdd}>切换待添加游戏</button> </div> ); }; export default App;
内容的提问来源于stack exchange,提问作者Guilherme
相关产品推荐
相关产品推荐

