【前端知识】React 基础巩固(二十八)——StrictMode

React 基础巩固(二十八)------StrictMode

StrictMode

  • StrictMode 是一个用来突出显示应用程序中潜在问题的工具

    • 与 Fragment 一样,StrictMode 不会渲染任何可见的 UI
    • 为后代出发额外的检测和警告
    • 严格模式检查仅在开发模式下运行,不影响生产构建
  • 严格模式检查什么?

      1. 识别不安全的生命周期
      1. 使用过时的 ref API
      1. 检查意外的副作用
      • 组件的 constructor 会被调用两次(生产环境不会),以查看逻辑代码被多次调用时是否产生副作用
      1. 使用废弃的 findDOMNode 方法
      1. 检测过时的 context API
      • 早期的 Context 是通过 static 属性声明 Context 对象属性,通过 getChildContext 返回 Context 对象等方式来使用 Context 的
  • 构建 App.jsx,通过子组件 Home 和 Profile 来查看严格模式和非严格模式的区别

javascript 复制代码
import React, { PureComponent, StrictMode } from "react";
import Home from "./pages/Home";
import Profile from "./pages/Profile";

export class App extends PureComponent {
  render() {
    return (
      <div>
        <StrictMode>
          <Home></Home>
        </StrictMode>

        <Profile></Profile>
      </div>
    );
  }
}

export default App;
  • Home.jsx
javascript 复制代码
import React, { PureComponent } from "react";

export class Home extends PureComponent {
  // 严格模式校验 ------ 识别不安全的生命周期
  UNSAFE_componentWillMount() {}

  // 严格模式校验 ------ 识别使用过时的ref API
  componentDidMount() {
    console.log(this.refs.title);
  }

  constructor(props) {
    super(props);
    // 严格模式校验 ------ 检查意外的副作用,执行两次
    console.log("Home componentDidMount");
  }

  render() {
    return <div ref="title">Home</div>;
  }
}

export default Home;
  • Profile.jsx
javascript 复制代码
import React, { PureComponent } from "react";

export class Profile extends PureComponent {
  // 非严格模式,正常使用
  UNSAFE_componentWillMount() {}

  //   非严格模式,正常使用
  componentDidMount() {
    console.log(this.refs.title);
  }

  constructor(props) {
    super(props);
    //   非严格模式,执行一次
    console.log("Profile componentDidMount");
  }

  render() {
    return (
      <div>
        Profile
        <h2 ref="title"></h2>
      </div>
    );
  }
}

export default Profile;
  • 查看比对结果
相关推荐
2分钟速写快排6 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge6668 小时前
JavaScript:BOM 详解
前端
Penge6668 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge6668 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge6669 小时前
Sass 了解
前端
Penge6669 小时前
Webpack 打包从 0 到 1 实战笔记
前端
Penge6669 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge6669 小时前
Ant Design(Antd)了解
前端
wangruofeng10 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github
Penge66610 小时前
JavaScript 核心语法速通
前端