reactjs - 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);
}
}, []);
}
我不太确定为什么它不起作用:(我首先将此代码分离到另一个函数中,首先我认为这就是它不起作用的原因。很快我意识到,这不是原因。
如果有人能提供帮助,真的很感激!
解决方案
原因在错误消息中。你不能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);
}
}, []);
}
推荐阅读
- php - 如何获取每个变体的库存数量 woocommerce
- selenium - 无头谷歌浏览器:如何防止网站知道他们的窗口是否聚焦
- read-the-docs - 版本未显示在 readthedocs 中
- dataframe - pyspark中有没有办法计算唯一值
- security - vmware中的Security Onion监控界面
- asp.net-core - 是否可以在“加载用户配置文件”= false 的共享主机中使用带有 asp.net 核心的身份服务器?
- laravel - 在基于引导的刀片模板中添加背景图像
- mysql - 在spring boot中将所有mysql表数据转换成JSON
- spring-security - 生成 JWT 令牌的 Spring Gateway
- mongodb - 在 MongoDB Cluster 错误验证设置中导入文件时出错:不兼容的选项:--file 和位置参数