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

时间:2021-05-03 13:15:02

标签: javascript reactjs asynchronous async-await react-hooks

我正在制作我的第一个自定义钩子,现在它应该只发送一个 GET 请求。这是钩子:

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}
};

我是这么称呼它的:(实际网址有点不同)

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

当我运行应用程序时,我得到一个无限循环,并按照我命名的顺序获取日志:首先我得到 1) 然后 2) >3),然后是 1) 等等......
就好像我从来没有收到过 fetch() 的回复一样。

我什至不知道问题是我对 async/await 还是某些 React 逻辑的理解。

有人知道这是怎么回事吗?

1 个答案:

答案 0 :(得分:1)

每次组件运行时,它都会调用这个自定义钩子,它进行一次获取然后改变状态,这使得组件运行并调用钩子等等。

您需要使用 useEffect 以便它只运行一次提取: 改变

  sendRequest();

到:

useEffect(sendRequest, []);