没有任何 API 数据的基本 React 组件渲染两次

Basic React component rendering twice without any API data

在我控制台的本地主机上,我看到我的组件被渲染了两次,但不知道为什么。我没有使用 componentDidMount 引入任何 API,它只是一个没有任何内容的基本组件。这是预期的吗?

当我提取 API 数据时,我在控制台中得到 4 次重新渲染,我希望在使用 componentDidMount 更新状态时看到另一个重新渲染。

我已经看到很多与导致重新渲染的状态更新相关的线程,但是找不到任何涵盖看起来很基本的东西的东西。

App.js

import React from "react";
import Testing from "./components/Body/Testing"

function App() {

  return (

    <div className="App">

      <Testing />

    </div>
  );
}

export default App;

Testing.js

import React, { Component } from 'react'

export class Testing extends Component {

    constructor(props) {
        super(props);
        this.counter = 0;
      }

    render() {

        this.counter++;
        console.log('render ' + this.counter)

        return (
            <div>Test</div>
        )

    }
}

export default Testing

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

我的控制台输出如下...

这是使用严格模式时的设计。其 React 的“检测意外副作用”功能。

https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

来自文档...

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

是的,React 正在双重渲染你的组件,以向你展示你正在做你不应该做的事情(在渲染中修改计数器)。

由于 React 无法知道您在渲染中做了什么,因此它认为双重渲染是使有缺陷的应用程序进入不良状态的最快方法。相当漂亮!