React - nextjs 在 useEffect 中调用自定义钩子
React - nextjs Calling custom hook in useEffect
我正在尝试调用 'useUser' 自定义挂钩,它使用 useEffect 和 useSWR; _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);
}
}, []);
}
我不太确定为什么它不起作用:(
我首先将这段代码分离到另一个函数中,首先我认为这就是它不起作用的原因。很快我意识到,这不是原因。
如果有人能提供帮助,我将不胜感激!
原因在错误消息中。您不能在 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);
}
}, []);
}
我正在尝试调用 'useUser' 自定义挂钩,它使用 useEffect 和 useSWR; _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);
}
}, []);
}
我不太确定为什么它不起作用:( 我首先将这段代码分离到另一个函数中,首先我认为这就是它不起作用的原因。很快我意识到,这不是原因。
如果有人能提供帮助,我将不胜感激!
原因在错误消息中。您不能在 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);
}
}, []);
}