我在两个状态变量中设置来自 api 的数据,这两个值是相同的。但是当我更新一个状态变量时,另一个状态变量也会发生变化。
Api.get("url")
.then((response) => {
this.setState(
{
deliveryInfoSection2: Object.assign({}, response.data),
deliveryInfoSection2copy: Object.assign({}, response.data),
}
);
})
updateState() {
try {
newVal = { ...this.state.deliveryInfoSection2 };
newVal.orderDetails[index].bo = value.replace(global.REG_NUMBER_ONLY, '');
//After this state variable deliveryInfoSection2copy is also updating.
this.setState({ deliveryInfoSection2: newVal }, () => {
if (this.state.deliveryInfoSection2.orderDetails[index].bo != '') {
}
catch (e) {
alert("error" + e)
}
}
最佳答案
这是与在 javascript 中使用扩展运算符时变量浅复制
有关的问题。和react的setState没有关系。扩展运算符为对象创建浅拷贝。
response = {
orderDetails: [
{
bo: "tempData1"
},
{
bo: "tempData2"
}
]
}
deliveryInfoSection2 = Object.assign({}, response)
deliveryInfoSection2Copy = Object.assign({}, response)
//Here spread operator will create shallow copy and so, the references are copied and hence any update to one will update other.
newVar = { ...deliveryInfoSection2 }
newVar.orderDetails[0].bo = "newValue"
deliveryInfoSection2 = newVar
console.log("deliveryInfoSection2", deliveryInfoSection2)
console.log("deliveryInfoSection2Copy", deliveryInfoSection2Copy)
要解决此问题,您需要创建对象的深拷贝。
您可以使用 JSON.parse(JSON.stringify(object)) 来实现相同的目的。
response = {
orderDetails: [
{
bo: "tempData1"
},
{
bo: "tempData2"
}
]
}
deliveryInfoSection2 = Object.assign({}, response)
deliveryInfoSection2Copy = Object.assign({}, response)
//This will create a deep copy for the variable
newVar = JSON.parse(JSON.stringify(deliveryInfoSection2))
newVar.orderDetails[0].bo = "newValue"
deliveryInfoSection2 = newVar
console.log("deliveryInfoSection2", deliveryInfoSection2)
console.log("deliveryInfoSection2Copy", deliveryInfoSection2Copy)
希望有帮助。如有任何疑问/困惑,请返回。
关于reactjs - 更新一个状态变量更改另一状态变量中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55547534/