React.StrictMode
严格模式可以为其后代元素触发额外的检查和警告,仅在开发模式下运行,不会影响生产构建。
React.StrictMode
本质上也是一个组件,自身不会渲染成任何可见的 UI。
严格模式下会检查:
- 不安全的生命周期:UNSAFE_componentWillMount 等。
- 过时的 ref API:字符串形式的 ref。
- 废弃的 findDOMNode 方法:在之前的 React API 中,可以通过 findDOMNode 来获取 DOM,目前已经不推荐这种方式了。
- 过时的 Context API:早期的 Context 是通过 static 声明 Context 对象属性,然后通过 getChildContext 返回 Context 对象等方式来使用 Context。
- 意外的副作用:严格模式下,组件的生命周期都会被执行两次,这是 React 为了让开发者查看编写的一些逻辑代码被调用多次时,是否会产生一些副作用。
import {StrictMode} from 'react'
import Home from './home'
class App extends PureComponent {
render() {
return (
<StrictMode>
<Home />
</StrictMode>
)
}
}
class Home extends PureComponent {
// 已过时的生命周期,在严格模式下会报错提醒
UNSAFE_componentWillMount() {
console.log('UNSAFE_componentWillMount')
}
render() {
return <h1>Home</h1>
}
}