谈谈React--componentWillReceiveProps的使用

什么是componentWillReceiveProps?

componentWillReceiveProps是React生命周期中的一个环节,有关React的生命周期,同窗们能够在这里详细了解。css

componentWillReceiveProps在初始化render的时候不会执行,它会在Component接受到新的状态(Props)时被触发,通常用于父组件状态更新时子组件的从新渲染。这个东西十分好用,可是一旦用错也会形成十分严重的后果。html

在componentWillReceiveProps这个回调函数中,咱们能够获取到就是props,经过this.props来获取,而后新的props则是经过函数的参数传入,在这里咱们能够比较两个props从而对本组件的state做出安全的变动而后从新渲染咱们的组件或者是触发子组件内的某些方法。react

//这种方式十分适合父子组件的互动,一般是父组件须要经过某些状态控制子组件渲染亦或销毁...

componentWillReceiveProps(nextProps) {//componentWillReceiveProps方法中第一个参数表明即将传入的新的Props
    if (this.props.sharecard_show !== nextProps.sharecard_show){
        //在这里咱们仍能够经过this.props来获取旧的外部状态
        //经过新旧状态的对比,来决定是否进行其余方法
        if (nextProps.sharecard_show){
            this.handleGetCard();
        }
    }
}
复制代码

上面是componentWillReceiveProps经常使用的方式,可是若是使用不当可能会致使如下后果,通常体现为组件陷入渲染死循环,他会一直接受新的外部状态致使自身一直在重渲染。安全

componentWillReceiveProps(nextProps) {
    if (this.props.sharecard_show !== nextProps.sharecard_show){
        if (nextProps.sharecard_show){
            this.handleGetCard();
        }
    }
}

handleGetCard() {
    this.props.test()
}

//父组件内

test() {
    this.setState({
        sharecard_show: !this.state.sharecard_show
    })
}
复制代码

一旦项目中出现这样的代码,有很大概率就会陷入死循环,这两个组件会一直在传递状态而且从新渲染,而后页面估计就卡挂了。这是其中一个须要注意的地方,另外咱们须要谨记,在componentWillReceiveProps中想做任何变动最好都将两个状态进行比较,假如状态有异才执行下一步。否则容易形成组件的屡次渲染,而且这些渲染都是没有意义的。函数

相关文章
相关标签/搜索