gpt4 book ai didi

reactjs - react-redux:更新嵌套状态中的特定位置

转载 作者:行者123 更新时间:2023-12-04 14:58:38 30 4
gpt4 key购买 nike

所以对于 TictacToe 游戏,我会在状态中有一个嵌套数组,如下所示:

field: [
[-1, -1, -1],
[-1, -1, -1],
[-1, -1, -1],
],

现在我想将一个特定的单元格设置为 X 或 O,但我无法让它完全重新呈现。我有 2 个功能组件,无论我尝试什么,我都无法更新单元格。 reducer 正确地更新了我的状态。那么我应该编写 reducer 还是更改任何内容,以便每个单元格在更改时重新呈现?

代码示例。显然还有更多,但我相信这应该足够了。

function Ttt_game(props){
return (
<div>
<table>
<tbody>
{
props.field.map((row, i) => (<Ttt_row row={row} key={i} row_index={i} />))
}
</tbody>
</table>
</div>
)
}

function Ttt_row(props){
return (
<tr>
{
row.map((cell, i) => (
<td key={i}>
<div onClick={() => insertIntoField({ x: row_index, y: i, symbol })}>
{cell}
</div>
</td>
))
}
</tr>
)
}

reducer :

case "ttt_insert":
let newField = state.field;
newField[action.payload.x][action.payload.y] = action.payload.symbol;
return {
...state,
field: newField
};

最佳答案

您正在改变字段对象,因此它不会更新。对象和数组是可变的,所以你必须创建新的数组;更新的那个。

下面是使用 .map 函数的例子。

你的 reducer 将是这样的:

const { field } = state;
const newField = field.map((row, rIndex) => {
if (rIndex !== action.payload.x) {
return row;
}
return row.map((col, cIndex) => {
if (cIndex !== action.payload.y) {
return col;
}
return action.payload.symbol;
})
})
return {
...state,
field: newField,
}

关于reactjs - react-redux:更新嵌套状态中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67398094/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com