我正在尝试使用 React 构建一个战舰游戏。
我的组件中有一个这样的状态,每个坐标都有一个包含两个“状态”的列表,如果其中没有船则为“空”(如果有则为“忙”),而坐标则为“完整”没有被击中(如果被击中,则为“击中”)。
this.state = {
status: {
A1: ['empty', 'intact'],
B1: ['busy', 'intact']
}
}
我想要做的是:当我单击战舰网格中的坐标来射击它时,我只想将列表中的第二个元素设置为“击中”,并保留第一个元素不变.
类似这样的事情:
handleClick = (e) => {
const coord = e.target.id; //get the coord from the element clicked, like 'A1'
this.setState({ status: { coord[1]: 'hit' } });
}
所以我希望我的新状态是:
this.state = {
status: {
A1: ['empty', 'hit'],
B1: ['busy', 'intact']
}
}
如何以正确的方式编写 this.setState({ status: { coord[1]: 'hit' } })
,以便我的新 State 与上面完全相同?
最佳答案
您可以使用属性访问器和切片来实现此目的。
例如:
handleClick = (e) => {
const coord = e.target.id; //get the coord from the element clicked, like 'A1'
const current = this.state.status[coord];
let newVal = current.slice(); // Clone array
newVal[1] = 'hit';
this.setState({ status: { ...this.state.status, [coord]: newVal } });
};
假设e.target.value
是一个字符串。
Here是 MDN 中有关属性访问器的文档。
关于javascript - 在组件中设置状态但仅更改列表中的第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51199732/