菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
0
0

React 生命周期变迁

原创
05/13 14:22
阅读数 275

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

发表评论

0/200
0 点赞
0 评论
收藏
为你推荐 换一批