Home >Web Front-end >Front-end Q&A >What are the newly added life cycles of react?
The newly added life cycles are: 1. getDerivedStateFromProps, used to control the process of props updating state; 2. getSnapshotBeforeUpdate, used to read the latest DOM data; 3. componendDidCatch.
The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.
When learning React, the life cycle is very important. After we understand each component of the life cycle, it will be of great help to write high-performance components.
The React life cycle is divided into three states 1 . Initialization 2. Update 3. Destruction
1. Abolition of life cycle
The official website document points out that code using these life cycles will be more likely to produce bugs in future versions of react, especially for asynchronous rendering versions
Since the asynchronous rendering mechanism will be adopted in the future, it will be Life cycle hook function removed in version 17
componentWillMount
componentWillRecieveProps
componentWIllUpdate
## 2. New life cycle
getDerivedStateFromProps(nextProps, prevState)
static getDerivedStateFromProps(nextProps, prevState) { const {type} = nextProps; // 当传入的type发生变化的时候,更新state if (type !== prevState.type) { return { type, }; } // 否则,对于state不进行任何操作 return null; }
getSnapshotBeforeUpdate()
componendDidCatch(error, info)
3. Basic use
class A extends React.Component { // 用于初始化 state constructor() {} // 用于替换 `componentWillReceiveProps` ,该函数会在初始化和 `update` 时被调用 // 因为该函数是静态函数,所以取不到 `this` // 如果需要对比 `prevProps` 需要单独在 `state` 中维护 static getDerivedStateFromProps(nextProps, prevState) {} // 判断是否需要更新组件,多用于组件性能优化 shouldComponentUpdate(nextProps, nextState) {} // 组件挂载后调用 // 可以在该函数中进行请求或者订阅 componentDidMount() {} // 用于获得最新的 DOM 数据 getSnapshotBeforeUpdate() {} // 组件即将销毁 // 可以在此处移除订阅,定时器等等 componentWillUnmount() {} // 组件销毁后调用 componentDidUnMount() {} // 组件更新后调用 componentDidUpdate() {} // 渲染组件函数 render() {} }[Related recommendations:
Redis Video tutorial】
The above is the detailed content of What are the newly added life cycles of react?. For more information, please follow other related articles on the PHP Chinese website!