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

4次阅读

共计 493 个字符,预计需要花费 2 分钟才能阅读完成。

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


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


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

我们在 render 函数中打印出 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})
        }
    }

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

正文完
 0