首页 > 解决方案 > React - nextjs 在 useEffect 中调用自定义钩子

问题描述

我正在尝试调用使用 useEffect 和 useSWR 的“useUser”自定义挂钩;_app.tsx 的内部 useEffect。但它抛出,

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

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        const params = {
          p1: "someText"
          m1: "someText02",
        };
    
        const { mutateUser } = useUser({
          redirectTo: "/test",
          redirectIfFound: true,
        });
    
        try {
          const fetchUser = async () => {
            mutateUser(
              await fetchJson("/api/login", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(params),
              })
            );
          };
          window && fetchUser();
        } catch (error) {
          console.error("An unexpected error happened:", error);
        }
      }, []);
}

我不太确定为什么它不起作用:(我首先将此代码分离到另一个函数中,首先我认为这就是它不起作用的原因。很快我意识到,这不是原因。

如果有人能提供帮助,真的很感激!

标签: reactjsreact-hooksnext.jsauthorizationuse-effect

解决方案


原因在错误消息中。你不能useUser在里面使用useEffect。您必须将其移动到功能组件的主体内。

function MyApp({ Component, pageProps }) {
    const { mutateUser } = useUser({
     redirectTo: "/test",
     redirectIfFound: true,
    });

    useEffect(() => {
        const params = {
          p1: "someText"
          m1: "someText02",
        };
    
        try {
          const fetchUser = async () => {
            mutateUser(
              await fetchJson("/api/login", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(params),
              })
            );
          };
          window && fetchUser();
        } catch (error) {
          console.error("An unexpected error happened:", error);
        }
      }, []);
}

推荐阅读