React class 组件渲染两次

React class component rendering twice

我已经按照代码创建了一个 class 组件。

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import Home from "./components/home";

ReactDOM.render(
  <React.StrictMode>
    <Home />
  </React.StrictMode>,
  document.getElementById("root")
);

serviceWorker.unregister();

home.jsx

import React, { Component } from "react";

class Home extends Component {
  state = {};

  render() {
    console.log("Render Home");
    return <h1>Home</h1>;
  }
}

export default Home;

如果我将它的主页更改为功能组件,那么它只会呈现一次。 但是为什么 class 组件渲染了两次?

答案就在关于严格模式的React docs中:

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

幸运的是,这仅适用于开发模式,因此您不会在生产中进行双重渲染。

不使用严格模式试试:

ReactDOM.render(
  <Home />,
  document.getElementById("root")
);