【React】关于父组件传prop值给子组件的state时,子组件state无法实时更新的解决方案

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

《【React】关于父组件传prop值给子组件的state时,子组件state无法实时更新的解决方案》
并在子组件中把接受到的prop值赋给state

《【React】关于父组件传prop值给子组件的state时,子组件state无法实时更新的解决方案》
当父组件点击Link进行传值时
子组件收到prop并调用render函数

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

《【React】关于父组件传prop值给子组件的state时,子组件state无法实时更新的解决方案》

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

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

componentWillReceiveProps

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

我们重写这个函数

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

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

《【React】关于父组件传prop值给子组件的state时,子组件state无法实时更新的解决方案》

    原文作者:无锡肖奈
    原文地址: https://segmentfault.com/a/1190000019672400
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞