簡體   English   中英

如何在 useEffect() 鈎子中使用異步方法

[英]how yo use an async method inside useEffect() hook

我需要在useEffect()獲取一個 api。 我嘗試這樣做,但它向我拋出以下錯誤: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

我的代碼如下:

-Api 我需要獲取:

export const fetchMyApi = async (code) => {
  const { data } = await useQuery("data", () =>
    clientAPIs.getData(code)
  );
  return data;
};

- 我的useEffect代碼:

  useEffect(() => {
    await fetchMyApi(values.code)
  }, [values]);

我在互聯網上發現了很多關於此的問題,但它們都提供了基本相同的解決方案,例如:

  useEffect(() => {
    fetchMyApi(values.code)
      .then((data) => {
        return data?.options;
      })
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, [values]);

要么

  useEffect(() => {
    let didCancel = false;
    async function fetch() {
      const result = await fetchMyApi(values.code);
      if (!didCancel) {
        console.log(result);
      }
    }
    fetch();
    return () => {
      didCancel = true;
    }; 
  }, [values]);

在我的情況下,這些都不起作用。 我正在使用Nextjs框架。

我應該嘗試什么?

錯誤:無效的掛鈎調用。 鈎子只能在函數組件的主體內部調用。

你打破了鈎子的規則。 鈎子僅在同步渲染 React 組件時被調用時有效。 效果在組件渲染后單獨運行。 所以你不能從效果中調用鈎子。

是的,你正在從一個效果中調用一個鈎子,因為這個效果:

  useEffect(() => {
    await fetchMyApi(values.code)
  }, [values]);

調用fetchMyApi函數,該函數調用一個鈎子:

await useQuery('data', () => /* ... */)

您錯誤地使用了反應查詢。

首先讓你的fetchMyApi只做它的異步任務,沒有別的:

export const fetchMyApi = (code) => {
  return clientAPIs.getData(code)
};

然后從功能組件的根調用useQuery

function MyComponent() {
  const { data } = useQuery('data', () => fetchMyApi('some code here'))
}

文檔應該帶你從這里開始

暫無
暫無

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

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