REACT生命周期:componentwillmount(), componentWillReceiveProps()替换方案

首先从最新的(16.4)React 生命周期官方文档可以看到现在我们就用这三个生命周期:

  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()

这三个生命周期几乎可以完成所有的需求,对于我这个刚接触REACT的菜鸡来说真是简单明了易上手啊!由于之前其他的生命周期都被舍弃了,如果继续用的话console里应该都会报unsafe warning(虽然不影响程序运行)下面是我的我的替换方案:

  1. componentwillmount() → componentDidMount()
    这个简单我就不贴示例代码了,直接替换生命周期的名字就行了,完全不需要改其他地方。(如果你改了之后出了bug,别急,后面的生命周期也要一起改)

  2. componentWillReceiveProps() → componentDidUpdate()
    修改前:

        componentWillReceiveProps(nextProps) {
           
            this.setState({
           
                data: nextProps.yourModels.data
            })
        }
    

    修改后:

        componentDidUpdate(prevProps) {
           
            if (prevProps.yourModels !== this.props.yourModels) {
           
                this.setState({
           
                    data: this.props.yourModels.data
                })
            }
        }
    

    可以看到实现这样的转换,除了要修改生命周期的名字,最重要的是把参数里的nextProps改成prevProps,然后在你的方法内部,原本所有nextProps都要替换成this.props
    if (prevProps.yourModels !== this.props.yourModels)这一行不能省略,如果删掉,会报错 Uncaught Error: Maximum update depth exceeded.
    REACT生命周期:componentwillmount(), componentWillReceiveProps()替换方案_第1张图片

你可能感兴趣的:(react,javascript,reactjs)