[英]React setState to update object
I have the following code我有以下代码
axios
.get("some.url")
.then(res => {
console.log(...res.data);
this.setState({
isLoaded: true,
assignmentData: {...res.data}
});
console.log(this.assignmentData) //this returns undefined
})
which fetches some data from the back-end and saves it to a state variable.它从后端获取一些数据并将其保存到状态变量中。 The data sent from the server is in the following format [{id:1, title:"abc"},{id:2,title:"bcd"}]
.服务器发送的数据格式如下[{id:1, title:"abc"},{id:2,title:"bcd"}]
。 However, the value of assignmentData
is not updated with the setState as the following console.log
returns undefined.但是, assignmentData
的值不会随 setState 更新,因为以下console.log
返回 undefined。
How can I update the assignmentData
state with the data received from the server?如何使用从服务器接收到的数据更新assignmentData
状态?
Firstly: assignmentData
will be added to the state this.state.assignmentData
首先:将assignmentData
添加到状态this.state.assignmentData
and secondly, this.setState(..)
is asynchronous.其次, this.setState(..)
是异步的。
If you want to view the data after it is set, you can do something like this:如果你想在设置后查看数据,你可以这样做:
this.setState({
isLoaded: true,
assignmentData: {...res.data}
}, () => {
console.log(this.state.assignmentData)
});
You're trying to access a value pertaining to the object that doesn't exist.您正在尝试访问与不存在的对象相关的值。 It exists in state
.它存在于state
。 Therefore you access as follows:因此,您可以按如下方式访问:
this.state.assignmentData
To access the value in your console log, supply your setState with a callback since it's async:要访问控制台日志中的值,请为 setState 提供回调,因为它是异步的:
this.setState({
isLoaded: true,
assignmentData: { ...res.data },
}, () => {
console.log(this.state.assignmentData);
});
log date in asynchronous callback of setState because setState is asynchronous在 setState 的异步回调中记录日期,因为 setState 是异步的
axios
.get("some.url")
.then(res => {
console.log(...res.data);
this.setState({
isLoaded: true,
assignmentData: {...res.data}
},() => console.log(this.state.assignmentData) );
})
Console in callback of setState because it's asynchronous控制台在 setState 的回调中,因为它是异步的
axios
.get("some.url")
.then(res => {
console.log(...res.data);
this.setState({
isLoaded: true,
assignmentData: {...res.data}
},()=>console.log(this.state.assignmentData));
})
or console inside render()
you will get updated state.或在render()
控制台,您将获得更新的状态。
try this尝试这个
axios.get("some.url")
.then(async(res) => {
console.log(...res.data);
await this.setState({
isLoaded: true,
assignmentData: {...res.data}
});
console.log(this.assignmentData);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.