生命周期:componentwillmount(), componentWillReceiveProps()替换方案(2023更新useEffect)"/>
REACT生命周期:componentwillmount(), componentWillReceiveProps()替换方案(2023更新useEffect)
2023更新:写了两年functionnal component,回头来看class based component,其实可以用useEffect()对应到这三种生命周期。
-
componentDidMount()
相当于useEffect(…,[]),在useEffect中使用空依赖,效果同样是在组件第一次evaluated & rendered的时候被调用,而且只调用这一次。 -
componentDidUpdate():
相当于useEffect(…,[someValue]),填了依赖的useEffect,当依赖someValue改变的时候,useEffect重新执行,组件被重新evaluated & rendered,依赖也随之被重新evaluated。 -
componentWillUnmount():
相当于useEffect(()=>{return()=>{…}},[]), useEffect中的cleanup,它会在组件从UI中remove的时候执行,看上去完美适配了componentWillUnmount这个生命周期的作用,但需要注意的是,useEffect多次执行的时候,cleanup其实会在第二次执行的时候也先执行一遍cleanup。 参考官方文档.html#cleaning-up-an-effect
2021更新:该死的react17.x现在不用生命周期了用hook function了喂!整个编程思维都要改变!从头学过吧朋友们!
首先从最新的(16.4)React 生命周期官方文档可以看到现在我们就用这三个生命周期:
- componentDidMount()
- componentDidUpdate()
- componentWillUnmount()
这三个生命周期几乎可以完成所有的需求,对于我这个刚接触REACT的菜鸡来说真是简单明了易上手啊!由于之前其他的生命周期都被舍弃了,如果继续用的话console里应该都会报unsafe warning(虽然不影响程序运行)下面是我的我的替换方案:
-
componentwillmount() → componentDidMount()
这个简单我就不贴示例代码了,直接替换生命周期的名字就行了,完全不需要改其他地方。(如果你改了之后出了bug,别急,后面的生命周期也要一起改) -
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()替换方案(2023更新useEffect)
发布评论