簡體   English   中英

當我使用反應鈎子時,API 被一遍又一遍地調用

[英]API is getting called over and over again when I am using react hooks

我正在使用React Hooks從現有的 API 獲取數據。 這是我的代碼

import React, { useState, useEffect } from "react";

export const People = () => {
  const [people, setPeople] = useState([]);
  const url = "http://127.0.0.1:5000/people";

  async function fetchData() {
    console.log("calling api .. ");
    const res = await fetch(url);
    res.json().then((res) => setPeople(res));
  }

  useEffect(() => {
    fetchData();
  });

  return (
    <div>
      <ul>
        {people &&
          people.map((person) => <li key={person.id}>{person.name}</li>)}
      </ul>
    </div>
  );
};

const Dashboard = (props) => {
  return (
    <div>
      <People />
    </div>
  );
};

export default Dashboard;

我遇到的問題是這個 API 被一遍又一遍地調用。 你能告訴我我在這里做錯了什么嗎?

謝謝

目前,使用useEffect(callback)將在每個 render執行回調。

嘗試將useEffect空的依賴項數組一起使用。

如果你想運行一個效果並且只清理一次,你可以傳遞一個空數組( [] )作為第二個參數。 這告訴 React 你的效果不依賴於 props 或 state 的任何值,所以它永遠不需要重新運行

  • 檢查我關於useEffect用例的其他答案
useEffect(() => {
  fetchData();
}, []);

至於組件的rest,應該是這樣的(認為):

// Should be on the outer scope as the URL is decoupled from the component's logic
const url = "http://127.0.0.1:5000/people";

export const People = () => {
  const [people, setPeople] = useState([]);

  useEffect(() => {
  // This way fetchData won't re-assigned on every render
    async function fetchData() {
      console.log("calling api .. ");
      const res = await fetch(URL);

      // Consitstance, don't mix `then` and `await` syntax
      const people = await res.json();
      setPeople(people);
    }

    fetchData();
  }, []);

  return (
    <div>
      <ul>
        {people &&
          people.map((person) => <li key={person.id}>{person.name}</li>)}
      </ul>
    </div>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM