我已经按照代码创建了一个类组件。
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/