reactjs - 如何立即更新状态变量
问题描述
我应该如何编码,以便我可以立即将 API 响应保存到状态并在 setState() 之外访问更新的响应。
state={
response: []
}
this.setState({
response: res // res is coming from API response
});
console.log(this.state.response); // it should show the API response instead of empty []
解决方案
使用回调:
...
this.setState({
response: res // res is coming from API response
}, function() {
console.log(this.state.response);
});
...