【前端知识】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,通过子组件 HomeProfile 来查看严格模式和非严格模式的区别

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;
  • 查看比对结果
相关推荐
李姆斯7 小时前
为啥Agent在coding表现这么好,但是在别的领域就是差的不少?
前端·agent·ai编程
鱼与宇9 小时前
前端Web(html+css+js+vue3)
前端
雪芽蓝域zzs11 小时前
(六)打包优化 + Nginx 部署完整配置 + 项目收尾
前端·vue.js
研☆香11 小时前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
东风破_11 小时前
JWT 1:从一个登录请求开始,理解 React 项目里的 API 层与 Mock
前端·后端
东风破_11 小时前
JWT 3:为什么 Token 要放进 Authorization?Axios 拦截器到底解决了什么?
前端·后端
东风破_11 小时前
JWT 5:路由守卫是什么?把整个 JWT 登录鉴权流程串起来
前端·后端
东风破_11 小时前
JWT 2:HTTP 是无状态的,为什么登录成功后还要给 Token?
前端·后端
东风破_12 小时前
JWT 4:Zustand 到底解决了什么?为什么登录状态要放进 Store?
前端·后端
IT_陈寒12 小时前
Vite动态导入差点让我秃头,原来问题出在这
前端·人工智能·后端