react教程,如何理解类组件生命周期基本逻辑之挂载?
发布于 作者:苏南大叔 来源:程序如此灵动~
千里迢迢,终于写到最基本的react生命周期的文章了,就是常见的componentWillUnmount、componentDidMount等函数。react版本更新到18,生命周期的设定也更新了好多次了。虽然有局部的react生命周期变化,但是这个"挂载"及"更新"的设定,一直保存了下来。

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文描述react@18环境下,传统的类组件中最常见的"挂载"及"卸载"相关生命周期。测试环境:create-react-app@5.0.1,react@18.2.0,react-dom@18.2.0,node@16.14.2。
特别强调
要点一:
本文描述的react环境是react@18下的类式组件,不同的react版本生命周期都有些不同点。所以,大家分析着理解就好。不一定和你真实的情况匹配。前主流推荐的函数式组件,里面并没有本文这些设定。在函数式组件里面,可能的解决方案是useEffect:
https://newsn.net/say/react-useeffect.html
要点二:
本文还是涉及了StrictMode的问题,和以前不同的是:本文的内容和是否开启StrictMode有关。
https://newsn.net/say/react-strict-mode.html

componentWillMount【已过期】【将要挂载】
对于react@18来说,这是个已经过期的生命周期。官方关于这个组件是如何unsafe的说明:
https://reactjs.org/link/unsafe-component-lifecycles
componentWillMount是个过期的生命周期名称,无论是否是严格模式,使用它就会得到一系列警告信息:

react-dom.development.js:86 Warning: componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.
* Move code with side effects to componentDidMount, and set initial state in the constructor.
* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.
Please update the following components: index
UNSAFE_componentWillMount【临时】【将要挂载】
根据提示信息,这个componentWillMount是个已经过期的生命周期,需要改成UNSAFE_componentWillMount。
在非严格模式下,这个UNSAFE_componentWillMount生命周期是【没有任何的警告信息】的。

而严格模式下,即使加上了UNSAFE_字样,依然有警告信息输出。

render【必备】【挂载渲染进行时】
不用在这个阶段实时处理state(意思是触发个异步操作,貌似可以),否则会死循环。

componentDidMount【常用】【组件挂载完成】
在这个【挂载完成】阶段实时处理state,【不会陷入】死循环。
这个生命周期是最常用的,在组件加载完毕后,做一些状态初始化之类的操作。一些副作用side effect操作也是放到这里的。

componentWillUnmount【组件即将卸载】
在前面的文章里面,可以知道,在这个componentWillUnmount阶段,可以用于一些清除副作用操作的逻辑。比如setInterval()或者setTimeout之类的异步操作。

测试代码
在这个文章里面,挂载了很多操作。特别设置了一个空组件,用于触发目标组件的卸载操作。两者通过rounter切换来复现挂载和卸载。路由相关的代码,就不给出了,苏南大叔以前的文章里面,有详细介绍:
import React, { Component } from 'react'
export default class index extends Component {
constructor(props) {
console.log("constructor");
super(props);
this.state = { msg: "苏南大叔" };
}
UNSAFE_componentWillMount() {
console.log("componentWillMount");
}
componentDidMount() {
console.log("componentDidMount");
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
console.log("render");
return (
<div>{this.state.msg}</div>
)
}
}
从图中可以看到,加载顺序是:
constructor => componentWillMount => render => componentDidMount卸载的事件就一个:
componentWillUnmount总结
更多react生命周期的经验文章,请点击: