在旧版本的react中(16.9)一下的版本中react的生命周期分为:
constructor/(getDefaultProps、getInitialState):使用class的方式创建使用static defaultProps = {}定义组件属性的默认值,constructor初始化组件状态;使用creatClass的方法创建组件,使用getDefaultProps定义组件属性值的默认值,使用geInitialState初始化组件的状态
componentWillMount:组件渲染前执行
componentDidMount:组件渲染后执行
componentWillReceiveProps:组件接收到新的属性后执行
shouldComponentUpdate:在确定组件需要更新,并准备去更新前执行,返回false则不更新组件
componentWillUpdate:组件更新前执行
componentDidUpdate:组件更新后执行
componentWillUnmount:组件卸载之前执行
在新版本中这些生命周期函数有一些改动,首先新版本弃用了componentWillMount、componentWillReceivePorps,componentWillUpdate这三个生命周期,非要使用也是可以的但是在使用过程中会报一个“has been renamed”的警告,这个时候有以下解决办法:
1.在报警告的生命周期函数前面加上前缀“UNSAFE_”,这个据说有插件可以完成
2.降低react和react-dom的版本到16.9一下,推荐使用16.4.1这个版本
3.使用react提供的新的生命周期函数替代
这里着重说第三种方式:
在新版本的react中提供了两个新的生命周期函数,getDerivedStateFromProps,getSnapshotBeforeUpdate来代替componentWillMount、componentWillReceivePorps,componentWillUpdate这三个生命周期函数,这两个版本的生命周期函数不能混用,并且getDerivedStateFromProps这个函数必须返回一个state,不然同样报错;
同时新增了componentDidCatch和static getDerivedStateFromError两个处理错误的方法,当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用两个方法;
并且新增了一个forceUpdate的api,这个api可以强制组件重新渲染,直接调用组件的render方法,所以如果是更新操作中使用了这个api的话,会阻断更新操作,去强制重新渲染组件
getDerivedStateFromProps:componentWillMount和componentWillReceviceProps的组件;当组件构建完成之后挂载渲染之前会调用;当接收到新的prop和state时会调用;每次接受到props后都要返回一个对象作为新的state,如果返回null则说明不需要更新state
getSnapshotBeforeUpdate:替代了componentWillUpdate的功能,接收参数是旧的props和旧的state;此生命周期函数的任何返回值,将作为参数传递给componentDidUpdate,作为componentDidUpdate的除了preProps和preState以外的参数;shouldComponentUpdate返回false后将不执行
static getDerivedStateFromError:在后代组件抛出异常或错误时触发,接收抛出的错误作为参数,并返回一个值用来更新state
componentDidCatch:在后代组件抛出异常或错误时触发,接收抛出的错误和异常组件的栈信息作为参数