我正在嘗試使用 React 制作一個簡單的游戲,例如紫色宮殿游戲中的紫色對。我有一個名為 的方法clickBtn,它應該在單擊時增加計數并在第二次單擊時減少,但我不知道為什么該handleClick方法會更改chosen以及clicked狀態屬性,即使在不使用方法的情況下制作了新狀態的副本setState。你能幫我解決這個問題嗎?class GameBoard extends React.Component { constructor() { super(); this.state = { score: 0, time: 0, list: [...generateObList(), ...generateObList()], count: 0 }; } handleClick = (id) => { this.clickBtn(id); const list = this.state.list.slice(); const current = list.find((a) => a.id === id); for (let x of list) { if (x.clicked && x.value == list.find((a) => a.id == id).value) { x.chosen = true; x.clicked = false; current.chosen = true; current.clicked = false; // this.setState((prev) => ({ // list: prev.list.map((el) => // el.id === id ? current : el.value === current.value ? x : el // ), // score: prev.score + 1 // })); } } }; clickBtn = (id) => { const current = this.state.list.slice().find((e) => e.id === id); let deClick = current.clicked; current.clicked = !current.clicked; console.log(current); this.setState( (prev) => ({ list: prev.list.map((el) => (el.id === id ? current : el)), count: prev.count + (deClick ? -1 : 1) }), () => { console.log(this.state.count, deClick, current); } ); }; render() { const boardStyle = { gridTemplateColumns: `repeat(5, 1fr)`, gridTemplateRows: `repeat(5,1r)` }; let list = this.state.list.map((n) => ( <Card value={n.value} onClick={(e) => { this.handleClick(n.id); }} show={!n.chosen} /> )); return ( <div class="gameBoard" style={boardStyle}> {list} </div> ); }}
對原始狀態的更改副本做出反應狀態更改?
holdtom
2023-07-20 17:25:13