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;
相关推荐
kyriewen1 天前
别再写useMemo了——2026年这5个React性能优化已经是反模式
前端·react.js·ai编程
索西引擎1 天前
【React】useReducer 与 useState 的比较研究:复杂状态管理场景下的选型
前端·react.js·前端框架
我是大卫1 天前
【图】React源码解析-从“上帝视角”俯瞰React的认知框架
前端·react.js·源码
我是大卫1 天前
【图】React源码解析-从源码数据结构、执行机制对比、闭包陷阱与最佳实践四个维度,深挖useMemo和useCallback的底层原理
前端·react.js·源码
索西引擎1 天前
【React】useState 函数式更新机制:闭包陷阱规避与状态一致性保障分析
前端·react.js·前端框架
用户298698530141 天前
前端实战:在 React 中使用 JavaScript 一键导出 Excel 图表与形状为图片
javascript·react.js·excel
索西引擎1 天前
【React】状态提升模式:设计原理、权衡分析与架构决策框架
前端·react.js·架构
不好听6132 天前
前端路由完全指南(下篇):懒加载、History 栈与工程化实践
前端·react.js
用户2814512549922 天前
React useState源码深度解析:Fiber、Hook链表与调度机制
react.js