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;
相关推荐
前端小书生24 分钟前
React 组件渲染
前端·react.js
用户7678797737323 小时前
后端转全栈之Next.js SEO优化
react.js·next.js
遂心_6 小时前
深入浅出 querySelector:现代DOM选择器的终极指南
前端·javascript·react.js
遂心_6 小时前
DOM元素内容修改全攻略:从innerHTML到现代API的最佳实践
前端·javascript·react.js
YiHanXii7 小时前
React.memo 小练习题 + 参考答案
前端·javascript·react.js
知识分享小能手18 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
虫虫rankourin1 天前
在 create-react-app (CRA) 创建的应用中使用 react-router-dom v7以及懒加载的使用方法
前端·react.js
开心不就得了1 天前
React 状态管理
react.js·typescript
天天进步20151 天前
掌握React状态管理:Redux Toolkit vs Zustand vs Context API
linux·运维·react.js
冷冷的菜哥1 天前
react实现无缝轮播组件
前端·react.js·typescript·前端框架·无缝轮播