React 生命周期变迁

React中组件提供了对应的生命周期支持,

定义组件的的方法:

  1. create-react-class模块
  2. class 类

它们之间的的区别这里就不展开了,具体可查看官方文档 区别,我们继续说生命周期

初次渲染

当组件初次渲染到DOM元素上时会调用以下方法:

constructor(props)

构造函数

static getDerivedStateFromProps

static getDerivedStateFromProps(props, state)
这是一个静态方法,它是访问不到组件的实例的,注意它是在state和props更新时都会触发的,不同于已被废弃的componentWillReceiveProps

render

渲染呈现,它是类组件内必须定义的方法

componentDidMount

虚拟DOM渲染到页面节点成功后调用

组件更新

当组件内state 或 传入的props 更改时会调用下面的方法:

static getDerivedStateFormProps(props, state)

同上

shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState)

这个方法我们比较常用,我们可以在通过this.props this.state取到 旧的props、state,可以与形参内的新的Props和state进行比较 返回true与false决定组件是否重新render

render

渲染装载节点

getSnapshotBeforeUpdate

getSnapshotBeforeUpdate(prevProps,prevProps)

Snapsshot 快照,在render 方法调用后应用到节点前调用此方法,我们可以在此方法内访问节点在更新前的一些数据,return 出去,我们可以在componentDidUpdate的第三个形参接收到我们return 出去的数据做进一步处理应用

componentDidUpdate

componentDidUpdate(prevProps, propsState, snapshot)

更新完成后调用,这里跟componentDidMount类似,可以做一些请求等操作

componentWillUnmount

组件卸载前调用,列如在组件内 setInterval 时 可以

错误捕捉

static getDerivedStateFromState

componentDidCatch

即将取消的生命周期

componentWillMount componentWillUpdate componentWillReceviedProps

本作品采用《CC 协议》,转载必须注明作者和本文链接
will
讨论数量: 1

现在有 hooks,写起来方便多了

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
1
粉丝
0
喜欢
0
收藏
0
排名:2310
访问:611
私信
所有博文
社区赞助商