React的严格模式StrictMode

StrictMode

严格模式只在开发环境下生效,当执行打包命令也就是生产环境下时,StrictMode会被去除。

React.StrictMode本身就是一个组件,该组件包含的子组件就会在开发环境下开启严格模式。

StrictMode严格模式作用

  1. 检测一些危险的操作,比如使用已经废弃的API和不推荐的API
  2. 会把生命周期函数都执行两次,来检测额外副作用
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;
相关推荐
whuhewei17 小时前
React搜索框组件
前端·javascript·react.js
红尘散仙1 天前
一套 Rust 核心,跑通 Tauri + React Native
react native·react.js·rust
贫民窟的勇敢爷们1 天前
React跨平台能力,打破前端开发的平台边界
前端·react.js·前端框架
朝阳391 天前
React【面试】
前端·react.js·面试
漓漾li1 天前
每日面试题(2026-05-15)- 前端
前端·vue.js·react.js
用户600071819102 天前
【翻译】在 React Router 中理清对话框
react.js
光影少年2 天前
react的 useState 原理、批量更新机制
前端·react.js·掘金·金石计划
Swift社区2 天前
Flutter / React / ArkUI:在鸿蒙 PC 上怎么选?
flutter·react.js·harmonyos
学习论之费曼学习法2 天前
ReAct框架深度解析:让Agent会思考再行动
前端·react.js·前端框架
openKaka_2 天前
completeWork:真实 DOM 是在哪里被创建的
前端·javascript·react.js