在 React 中,如何按值复制状态 属性?
In React, how do I copy a state property by value?
我正在构建 React 16.13 应用程序。我想从我的状态中复制一个 属性 以便对其进行操作并保持基础状态不变。我认为这是做到这一点的方法...
async handleFormSubmit(e) {
e.preventDefault();
const NC = [...this.state.newCoop]
delete NC.addresses[0].country;
try {
const response = await fetch(FormContainer.REACT_APP_PROXY + "/coops/", {
method: "POST",
body: JSON.stringify(this.state.newCoop),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
然而这一行
const NC = [...this.state.newCoop]
报错
Unhandled Rejection (TypeError): this.state.newCoop is not iterable
按值复制状态变量的正确方法是什么?
我认为这只是因为您将对象展开到数组中;只是做:
const NC = {...this.state.newCoop}
编辑:
关于深拷贝的问题,可以看看这个回答:
顺便说一句,这与反应无关:)
我正在构建 React 16.13 应用程序。我想从我的状态中复制一个 属性 以便对其进行操作并保持基础状态不变。我认为这是做到这一点的方法...
async handleFormSubmit(e) {
e.preventDefault();
const NC = [...this.state.newCoop]
delete NC.addresses[0].country;
try {
const response = await fetch(FormContainer.REACT_APP_PROXY + "/coops/", {
method: "POST",
body: JSON.stringify(this.state.newCoop),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
然而这一行
const NC = [...this.state.newCoop]
报错
Unhandled Rejection (TypeError): this.state.newCoop is not iterable
按值复制状态变量的正确方法是什么?
我认为这只是因为您将对象展开到数组中;只是做:
const NC = {...this.state.newCoop}
编辑:
关于深拷贝的问题,可以看看这个回答:
顺便说一句,这与反应无关:)