我需要使用传播运算符在以下状态内更新数据。
必须这样进行:data[0]
应该用"vehOn":"Finance"
let state = {
"data": [{
"year": "2017",
"make": "ALFA ROMEO",
"model": "ILX 4D 2.0 PREMIUM PACKAGE"
}],
"error": ""
};
修改状态应为:
let modifiedstate = {
"data": [{
"year": "2017",
"make": "ALFA ROMEO",
"model": "ILX 4D 2.0 PREMIUM PACKAGE",
"vehOn": "Finance"
}],
"error": ""
};
答案 0 :(得分:1)
根据documentation,我看到的唯一一种达到您结果的方法是:
let state = {
"data": [{
"year": "2017",
"make": "ALFA ROMEO",
"model": "ILX 4D 2.0 PREMIUM PACKAGE"
}],
"error": ""
};
let modifiedstate = { "data": [{ ...state.data[0], ...{vehOn: "Finance"} }],
"error": ""};
console.log(modifiedstate);
答案 1 :(得分:1)
const state = {
"data": [{
"year": "2017",
"make": "ALFA ROMEO",
"model": "ILX 4D 2.0 PREMIUM PACKAGE"
}],
"error": ""
};
console.log("---- state ----");
console.log(state);
const modifiedstate = { ...state,
data: state.data.map((entry, i) => i === 0 ? ({ ...entry,
vehOn: "Finance"
}) : entry)
};
console.log("---- modifiedstate ----");
console.log(modifiedstate);
答案 2 :(得分:0)
如果您打算创建一个与状态相同的对象,并且您不知道state
可以拥有哪些属性,则应该寻找一种方法来deep clone it
否则,如果您完全确定state
的结构并想要进行简单的克隆,则可以执行以下操作:
let modifiedstate = "data": [{
...state.data[0],
"vehOn": "Finance"
}],
"error": ""
}