reactjs 有人知道为什么componentDidMount方法会运行2次吗?

hts6caw3  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(186)

有人知道为什么组件DidMount运行2次吗?
当我调用组件did mount方法时,这个console.log()被打印了两次

import React, { Component } from "react";
import ClientsTable from "../components/Table/ClientsTable";
import CreateClientModal from "../components/Modal/CreateClientModal";
import AuthContext from "../context/auth-context";

class Clients extends Component {
  static contextType = AuthContext;

  state = {
    clients: [],
  };

  componentDidMount() {
    this.fetchClients();
  }
  fetchClients() {
    let requestBody = {
      query: `
                query{
                  users{
                    _id
                    name
                  }
                }
            `,
    };

    fetch("http://localhost:8000/api", {
      method: "POST",
      body: JSON.stringify(requestBody),
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + this.context.token,
      },
    })
      .then((res) => {
        if (res.status !== 200) {
          throw new Error("Failed");
        }
        return res.json();
      })
      .then((resData) => {
        const clients = resData.data.users;
        this.setState({ clients: clients });
        console.log(resData);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  render() {
    const clientsList = this.state.clients;
    const authData = {
      token: this.context.token,
      userId: this.context.userId,
      companyId: this.context.companyId,
    };
    return (
      <div>
        <h1>Clients Page</h1>
        <CreateClientModal authData={authData} />
        <ClientsTable value={clientsList} />
      </div>
    );
  }
}
export default Clients;

我不知道为什么它运行了两次,它应该只运行一次。我试图从我的数据库中获取所有客户端,但它做了两次。
如果有人能帮助我,我将不胜感激,因为我已经坚持了相当长的一段时间

mnemlml8

mnemlml81#

我刚刚意识到组件在严格模式下运行时会运行两次。

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

当我完美地删除<React.StricMode>作品!

相关问题