简体   繁体   English

当我使用反应钩子时,API 被一遍又一遍地调用

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

I am using React Hooks to get data from an existing API.我正在使用React Hooks从现有的 API 获取数据。 Here is my code这是我的代码

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;

The problem that I am having is this API is getting called over and over again.我遇到的问题是这个 API 被一遍又一遍地调用。 Can you please let me know what I am doing wrong here.你能告诉我我在这里做错了什么吗?

Thanks谢谢

Currently, using useEffect(callback) will execute the callback on every render .目前,使用useEffect(callback)将在每个 render执行回调。

Try using useEffect with an empty dependencies array .尝试将useEffect空的依赖项数组一起使用。

If you want to run an effect and clean it up only once , you can pass an empty array ( [] ) as a second argument.如果你想运行一个效果并且只清理一次,你可以传递一个空数组( [] )作为第二个参数。 This tells React that your effect doesn't depend on any values from props or state, so it never needs to re-run .这告诉 React 你的效果不依赖于 props 或 state 的任何值,所以它永远不需要重新运行

  • Check my other answer on useEffect use cases.检查我关于useEffect用例的其他答案
useEffect(() => {
  fetchData();
}, []);

As for the rest of the component, it should look like so (opinioned):至于组件的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.

相关问题 我得到输入字符串的格式不正确,尽管我一遍又一遍地使用相同的格式 - I am getting Input string was not in a correct format although i used the same format over and over again 为什么在使用 React hooks 获取 api 时我会得到一个空数组? - Why am i getting and empty array when fetching an api with react hooks? 一遍又一遍地调用函数? - Function called over and over again? 我是否在此jQuery代码中一再绑定事件? - Am I binding events over and over again in this jQuery code? 为什么我收到此错误“React 检测到 SidebarDesktop 调用的 Hooks 的顺序发生了变化”? - Why I am getting this error “React has detected a change in the order of Hooks called by SidebarDesktop”? 为什么在尝试循环下一个 js 页面中的数据(使用 getStaticProps)时我得到未定义? - Why am I getting undefined when attempting to loop over data in next js page (using getStaticProps)? 使用 reactjs 钩子时,为什么会出现“TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function”错误? - Why am I getting "TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function" error when using reactjs hooks? 我正在为我的应用程序使用Firebase身份验证。 似乎有一个无限循环,页面不断被重定向 - I am using Firebase authentication for my application. There seems to be an infinite loop where the page keeps being redirected over and over again 我是不是用错了 React hooks? - Am I using React hooks wrong? .on事件不断被解雇 - .on event keeps getting fired over and over again
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM