我试图设置一个新的状态,但唯一改变的是这个数组中的一个元素。我对 javascript 还很陌生,所以我不太明白如何执行语法。
我知道我可以使用扩展运算符创建一个新对象,并且可以在对象中添加/更改某些内容(如果它位于顶层),但我该如何在数组中执行操作
newRow = {
name: "kevin"
status: false
}
currentStageData = {
name: "Stage 1"
items: [
{
name: "david"
status: true
},
{
name: "kevin"
status: true
},
{
name: "bruce"
status: true
},
]
}
我尝试这样做,但这种语法不起作用。
var newCurrentStageData = { ...currentStageData, newCurrentStageData.items[index]: newRow }
所以我最终不得不这样做。
var newRow = { ...row, status: e.target.checked }
var newCurrentStageData = { ...currentStageData }
newCurrentStageData.items[index] = newRow
最佳答案
展开在这里不起作用,因为您要插入项目的索引不一定位于末尾或开头。
您当前的方法还通过改变状态来违反 React 规则,这是绝对不应该做的。
如果索引已存在于数组中,.map
创建一个新索引,并在满足条件时替换同一索引处的项目。
const newCurrentStageData = { ...currentStageData, items: currentStageData.items.map((item, i) => i === index ? newRow : item) };
但我真的不会把所有内容都写在一行上。可读性比行压缩更重要。
const newCurrentStageData = {
...currentStageData,
items: currentStageData.items.map(
(item, i) => i === index ? newRow : item
)
};
关于javascript - 使用 JavaScript React 中的扩展运算符将数组中的元素替换为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70193509/