【问题标题】:React - nextjs Calling custom hook in useEffectReact - nextjs 在 useEffect 中调用自定义钩子
【发布时间】:2021-09-10 12:35:22
【问题描述】:

我正在尝试调用使用 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);
        }
      }, []);
}

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

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

【问题讨论】:

  • 错误信息是否不够清楚说明问题所在?您只能从功能组件或其他钩子的主体中调用 React 钩子。 注意 useEffect 回调函数不是 React 钩子,并且违反了关于钩子的其他规则不在循环、条件和嵌套函数中调用。见Rules of Hooks

标签: reactjs react-hooks next.js authorization use-effect


【解决方案1】:

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

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);
        }
      }, []);
}

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 2022-10-09
    • 2020-03-23
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2020-05-19
    相关资源
    最近更新 更多