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;
相关推荐
lvchaoq11 小时前
react 修复403页面无法在首页跳转问题
前端·javascript·react.js
郝开11 小时前
6. React useState基础使用:useState修改状态的规则;useState修改对象状态的规则
前端·javascript·react.js
Codigger官方11 小时前
Linux 基金会牵头成立 React 基金会:前端开源生态迎来里程碑式变革
linux·前端·react.js
ObjectX前端实验室12 小时前
【图形编辑器架构】🧠 Figma 风格智能选择工具实现原理【猜测】
前端·react.js
技术钱12 小时前
react+andDesign+vite+ts从零搭建后台管理系统(三)-Layout布局
javascript·react.js·ecmascript
郝开13 小时前
7. React组件基础样式控制:行内样式,class类名控制
react.js
进阶的鱼17 小时前
React+ts+vite脚手架搭建(四)【mock篇】
前端·javascript·react.js
Keepreal49618 小时前
word文件预览实现
前端·javascript·react.js
郝开18 小时前
5. React中的组件:组件是什么;React定义组件
前端·javascript·react.js
Keepreal49621 小时前
pdf文件预览实现
javascript·react.js