2

问题描述:
在写项目的时候碰到这样一个问题
通过Link组件传递一个名为“name”的state给子组件

clipboard.png
并在子组件中把接受到的prop值赋给state

clipboard.png
当父组件点击Link进行传值时
子组件收到prop并调用render函数

我们在render函数中打印出state值
发现state值始终没有改变

clipboard.png

问题分析
由于react的setstate方法是异步执行的,所以render函数并没有收到更新的state值

解决方法
react生命周期中有这样一个函数

componentWillReceiveProps

componentWillReceiveProps在初始化render的时候不会执行,它会在Component接受到新的状态(Props)时被触发,一般用于父组件状态更新时子组件的重新渲染。

我们重写这个函数

    componentWillReceiveProps(nextProps) {
        if(nextProps.location.state!=undefined){
            this.setState({
                activekey: nextProps.location.state.name
            })
        }
    }

发现可以获取到实时的数据了

clipboard.png


无锡肖奈
186 声望7 粉丝

十八线野生程序猿 前端开发