node.js - 如何在 useEffect() Hook 中使用异步方法

标签 node.js reactjs typescript next.js

我需要在 useEffect() 中获取 API。我尝试这样做,但它引发了以下错误:错误:无效的 Hook 调用。钩子(Hook)只能在函数组件的主体内部调用。

我的代码如下:

-我需要获取的 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 框架。

我应该尝试什么?

最佳答案

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

你违反了 hooks 规则。 Hooks 仅在同步渲染 React 组件时调用时才有效。效果在组件渲染后单独运行。因此您无法从效果中调用 Hook 。

是的,您正在从效果中调用 Hook ,因为该效果:

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

调用fetchMyApi函数,该函数调用一个钩子(Hook):

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

您错误地使用了 react 查询。

首先让您的 fetchMyApi 只执行异步任务,而不执行其他操作:

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

然后从功能组件的根调用useQuery:

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

The documentation应该带你从这里走完剩下的路

关于node.js - 如何在 useEffect() Hook 中使用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68489294/

相关文章:

node.js - Gulp require(Path) 与 fs.existsSync(Path) 不同

javascript - Node JS 安装提前结束

javascript - react-bootstrap:清除元素值

typescript - IONIC httpclient 提供者,数据消失

typescript - 动态 Typescript 对象属性

node.js - 在结束响应之前如何输出数据?

node.js - 找不到模块'source-map-support/register

javascript - react 不覆盖状态

javascript - setState 一个对象数组,根据 id 更新对象中的两个值

typescript - 在带有 TypeScript 的 Next.js 中使用 getInitialProps