答案 0 :(得分:0)
您需要将setState
与callback
一起使用
根据官方文档
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