有人知道为什么`componentDidMount`方法运行两次吗?

huangapple go评论50阅读模式
英文:

Did someone knows why the componentDidMount method its running 2 times?

问题

有人知道为什么componentDidMount方法运行两次吗?

当我调用componentDidMount方法时,我会看到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;

我不知道为什么它运行两次,它应该只运行一次。我尝试从数据库中获取所有客户端,但它运行两次。如果有人可以帮助我,我将不胜感激,因为我已经被这个问题困扰了很长时间。

英文:

Someones knows why the componentDidMount runs 2 times?

I get this console.log() printed 2 times when I call the component did mount method

import React, { Component } from &quot;react&quot;;
import ClientsTable from &quot;../components/Table/ClientsTable&quot;;
import CreateClientModal from &quot;../components/Modal/CreateClientModal&quot;;
import AuthContext from &quot;../context/auth-context&quot;;
class Clients extends Component {
static contextType = AuthContext;
state = {
clients: [],
};
componentDidMount() {
this.fetchClients();
}
fetchClients() {
let requestBody = {
query: `
query{
users{
_id
name
}
}
`,
};
fetch(&quot;http://localhost:8000/api&quot;, {
method: &quot;POST&quot;,
body: JSON.stringify(requestBody),
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;,
Authorization: &quot;Bearer &quot; + this.context.token,
},
})
.then((res) =&gt; {
if (res.status !== 200) {
throw new Error(&quot;Failed&quot;);
}
return res.json();
})
.then((resData) =&gt; {
const clients = resData.data.users;
this.setState({ clients: clients });
console.log(resData);
})
.catch((err) =&gt; {
console.log(err);
});
}
render() {
const clientsList = this.state.clients;
const authData = {
token: this.context.token,
userId: this.context.userId,
companyId: this.context.companyId,
};
return (
&lt;div&gt;
&lt;h1&gt;Clients Page&lt;/h1&gt;
&lt;CreateClientModal authData={authData} /&gt;
&lt;ClientsTable value={clientsList} /&gt;
&lt;/div&gt;
);
}
}
export default Clients;

I dont know why its running 2 times, it should run only one time.
Im tryng to fetch all clients from my db but its doing it 2 times.

If somone can help me I will be grateful since I have been stuck with this for quite a while

答案1

得分: 0

我刚刚意识到,当在"Strict Mode"下运行时,组件会运行两次。
我刚刚修改了我的index.js文件。

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.StrictMode>时,一切都运行得很完美!

英文:

I just realized that compontents run twice when running on Strict Mode.
I just change my index.js

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom/client&#39;;
import &#39;./index.css&#39;;
import App from &#39;./App&#39;;
const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));
root.render(
&lt;React.StrictMode&gt;
&lt;App /&gt;
&lt;/React.StrictMode&gt;
);

and when I remove the <React.StricMode> works perfectly!

huangapple
  • 本文由 发表于 2023年2月6日 06:41:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定