简体   繁体   English

在自定义反应钩子中使用 fetch() 的无限循环

[英]Infinite loop using fetch() in a custom react hook

I am making my first custom hook,for now it should just send a GET request.我正在制作我的第一个自定义钩子,现在它应该只发送一个 GET 请求。 This is the hook:这是钩子:

const useMyCustomHook = request => {
  
  // I have a couple of useState() here

  const sendRequest = async () => {

    // I set the states here

    try {
      console.log("2) This log shows up.");
      const response = await fetch(request.url);
      console.log("This does NOT shows up.");
      if (!response.ok) throw new Error('Something went wrong');

      // I reset the states here

    } catch(error) {
      console.log(error);
    }
  }; // end sendRequest()

  console.log("1) This log shows up.");
  sendRequest();
  console.log("3) This log shows up.");

  return {infoFromTheStates}
};

And that's how I call it: (The actual url is a bit different)这就是我所说的:(实际的 url 有点不同)

const response = useSendRequest({url: 'https://react-http-b228c-default-rtdb.europe-west1.firebasedatabase.app/tasks.json'});

When I run the app I get an infinite loop and I get the logs in the order I named them: first I get 1) then 2) and 3) , then again 1) and so on...当我运行应用程序时,我得到一个无限循环,并按照我命名它们的顺序获取日志:首先我得到1)然后2)3) ,然后又是1)等等......
It's like I never arrive to get a response from fetch() .就好像我从来没有来过fetch()的回应。

I don't even know if the problem is my understanding of async/await or of some React logic.我什至不知道问题是我对 async/await 还是某些 React 逻辑的理解。

Anyone knows what's going on?有谁知道发生了什么?

Each time the component runs, it calls this custom hook, which makes a fetch and then change the state, which makes the component run and it calls the hook and so on.每次组件运行时,它都会调用这个自定义钩子,它会进行一次获取,然后更改 state,这会使组件运行并调用钩子等等。

You need to use useEffect so that it will only run the fetch once: change您需要使用 useEffect 以便它只运行一次提取:更改

  sendRequest();

to:至:

useEffect(sendRequest, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM