reactjs - React 类组件渲染两次

标签 reactjs render

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

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;

如果我将 Home 更改为功能组件,那么它只会渲染一次。 但为什么类组件会渲染两次呢?

最佳答案

答案就在 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

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

关于reactjs - React 类组件渲染两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61715632/

相关文章:

javascript - 使用 firebase 创建用户时设置显示名称

javascript - 使用点击功能 react JS 渲染元素并将索引传递给点击功能

javascript - 使用 Typescript 的 DeviceMotionEvent 请求权限

javascript - 如何在 Ruby on Rails 4 中通过 CoffeeScript 进行渲染

reactjs - 将 OIDC 添加到具有受限路由的 React 应用程序

reactjs - 在带有 TypeScript 的 next.js 中使用 Router 的空安全方法

html - 来自其他 Controller 的调用的 MVC : Get HTML string From Controller/Action,

reactjs - React Native : when you navigate away from a component, 该组件曾经被卸载过吗?

python - Pygame 文本不渲染

java - 光滑2d |渲染和更新的最佳方式