美文网首页
react学习笔记:在react生命周期componentWil

react学习笔记:在react生命周期componentWil

作者: 顾北枳 | 来源:发表于2019-03-17 21:21 被阅读0次

    在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值了

    相关文章

      网友评论

          本文标题:react学习笔记:在react生命周期componentWil

          本文链接:https://www.haomeiwen.com/subject/sijpmqtx.html