如何在React状态下更新嵌套对象?

时间:2020-04-18 11:46:33

标签: javascript node.js reactjs

有人可以告诉我我在做什么错吗?从console.log中,我可以看到date函数正常工作。但是,即使在this.setState之后,时间戳也不会更新。提前致谢!

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要将setStatecallback一起使用

根据官方文档

setState()并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用setState()之后立即读取this.state可能是一个陷阱。而是使用componentDidUpdate或setState回调(setState(updater,callback)),确保在应用更新后均可以触发其中的一种。

this.setState((prevState)=>{
   userInfo:{
       ...prevState.userInfo,
       timestamp:timestamp
},()=>console.log(this.state.userInfo.timestamp)) // console.log here as setState is async operation