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;
相关推荐
张元清2 小时前
React useMount Hook:只在挂载时执行一次的正确姿势 (2026)
javascript·react.js
只一3 小时前
React 性能优化精讲:useCallback 与 useMemo 彻底吃透(附实战案例)
前端·react.js
YIAN3 小时前
吃透这 5 个核心点,你的 React+TS 代码直接上一个台阶
前端·react.js·typescript
小林ixn3 小时前
从混乱到清晰:项目架构与自定义 Hook 的双重实践
react.js·架构·前端框架
breeze jiang5 小时前
React + WebGPU 在浏览器运行 DeepSeek:从 Worker 通信到流式生成
前端·javascript·react.js
小林ixn5 小时前
前端卡顿终结者:用 useRef 把 Web Worker 请进 React 项目
前端·react.js·前端框架
sunly_5 小时前
React 三个重要概念:Ref、Props、State 详解
前端·javascript·react.js
To_OC17 小时前
别只拿 useRef 绑 DOM 了,搭配 Web Worker 解决页面卡顿才是真的香
前端·react.js·dom
小当家.10519 小时前
深入理解 ReAct Agent:从原理到 Java 实战
java·react.js·agent·react·架构设计·agent设计
阿黎梨梨1 天前
React 表单处理与性能优化:从入门到进阶
前端·react.js