react学习笔记:在react生命周期componentWillMount中无法setState的解决办法

在componentWillMount中去setState,然后打印出来发现state没有改变

比如

componentWillMount(){

        const height = window.innerHeight;

        this.setState({

            height: height

        })

   console.log(this.state.height) 

    }

后台结果显示height还是原来的值,因为setState是异步的,他会在render后才生效,

想要打印出setState之后的值 需要在setState方法中加入一个回调函数,比如

componentWillMount(){

        const height = window.innerHeight;

        this.setState({

            height: height

        },()=>console.log(this.state.height))

    }

这样打印出来的就是最开始定义的height值了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容