StrictMode
严格模式只在开发环境下生效,当执行打包命令也就是生产环境下时,StrictMode
会被去除。
React.StrictMode
本身就是一个组件,该组件包含的子组件就会在开发环境下开启严格模式。
StrictMode严格模式作用
- 检测一些危险的操作,比如使用已经废弃的API和不推荐的API
- 会把生命周期函数都执行两次,来检测额外副作用
js
// App.js
import { PureComponent } from 'react'
class App extends PureComponent {
constructor(props) {
super(props)
this.state = {
msg: "hello App"
}
console.log("constructor 运行")
}
static getDerivedStateFromProps(props, state) {
console.log(props, state);
console.log("getDerivedStateFromProps 运行");
return null;
}
render() {
console.log("render 运行")
return (
<div>
<h1>App组件</h1>
</div>
)
}
componentDidMount() {
console.log("componentDidMount 运行")
}
}
export default App;
js
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
去掉严格模式:
js
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
js
// App.js
import { PureComponent } from 'react'
class App extends PureComponent {
constructor(props) {
super(props)
this.state = {
msg: "hello App"
}
console.log("constructor 运行")
}
static getDerivedStateFromProps(props, state) {
console.log(props, state);
console.log("getDerivedStateFromProps 运行");
return null;
}
render() {
console.log("render 运行")
return (
<div>
<h1>App组件</h1>
</div>
)
}
componentDidMount() {
console.log("componentDidMount 运行")
}
}
export default App;