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)
}
}
答案 0 :(得分:1)
这是关于JavaScript中的shallow copy of variables while using spread operator
的问题。它与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)
希望有帮助。恢复任何疑问/困惑。