前言
正在努力学习 React 框架中,在写练习 demo 时发现组件生命周期函数连续渲染两次,百思不得其解,于是各种谷歌百度,终于了解了原因,在此记录一下。
一、解决办法
先看代码:
import React from 'react'
interface PropsType {
[key: string]: any
}
class ComTest extends React.Component {
timer: NodeJS.Timer | null = null
componentDidMount() {
this.timer = setInterval(() => {
console.log('时间控制器');
}, 1000)
}
componentWillUnmount() {
console.log('componentWillUnmount')
clearInterval(Number(this.timer))
}
render(): React.ReactNode {
return (
<>
<p>组件卸载测试</p>
</>
)
}
}
export default class Lifecycle extends React.Component<PropsType> {
constructor(props: PropsType) {
super(props)
console.log('constructor')
}
state = {
count: 0,
flag: true
}
componentDidMount() {
console.log('componentDidMount')
}
componentDidUpdate() {
console.log('componentDidUpdate')
}
addCount = () => {
this.setState({
count: this.state.count + 1
})
}
unMountTest = (flag: boolean) => {
this.setState({
flag
})
}
render(): React.ReactNode {
console.log('render');
return (
<>
生命周期
<p>数字:{this.state.count}</p>
<button onClick={this.addCount}>+</button>
{this.state.flag ? <ComTest></ComTest> : null}
<button onClick={() => this.unMountTest(false)}>卸载test</button>
<button onClick={() => this.unMountTest(true)}>加载test</button>
</>
)
}
}
如上代码,在加载页面时,发现 componentDidMount 生命周期函数连续调用两次,截图如下:
解决这个问题,只需要将 index.tsx 文件中的严格模式组件 React.StrictMode 去掉即可。
注释之后,执行效果如下,生命周期函数只调用一次。
二、原因
上面只是说了解决办法,这里说一下为什么。
StrictMode 是一个用来检查项目中潜在问题的工具。StrictMode 不会渲染任何可见的 UI,它为其后代元素触发额外的检查和警告。
注意:严格模式检查仅在开发模式下运行;它们不会影响生产构建。
StrictMode 目前有助于:
1、识别不安全的生命周期;
2、关于使用过时字符串 ref API 的警告;
3、关于使用废弃的 findDOMNode 方法的警告;
4、检测意外的副作用;
5、检测过时的 context API。
最后,回归到本文的问题:组件的一次更新流程,在视图真正刷新之前的部分都是可能被多次调用的,因而这些部分中不能出现副作用,开发环境下会刻意触发两次以使得开发者能注意到误用的副作用。