11. this.setState更新问题

this.setState是异步的,所以在this.setState之后不能立刻得到最新的state数据
关于如何获取最新的数据,有如下三种方法

1.回调函数

this.setState({
  xxx:'xxx',
}, () => {
  console.log(this.state.xxx) });

2.利用组件生命周期函数componentDidUpdate

3.利用setTimeout 延迟为0

当setTimeout 延迟为0时

componentDidMount () {
        console.log('a');
        setTimeout(function(){ console.log('b'); },0); console.log('c'); console.log('d'); }
 

猜你喜欢

转载自www.cnblogs.com/wangrui38/p/9241954.html