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

StrictMode是一个开发期间的辅助工具,用于突出显示可能的问题,如不安全的生命周期方法、过时的refAPI和意外的副作用。它会在构造函数中调用两次以检查副作用,并警告关于废弃的findDOMNode方法和早期ContextAPI的使用。通过在Home组件中使用StrictMode,可以看到组件生命周期方法和refAPI的额外检查,而在Profile组件中则没有这种行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 来查看严格模式和非严格模式的区别

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
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
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;
  • 查看比对结果
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端Outman

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值