Ser*_*eis 27 javascript reactjs react-hooks
现在我正在使用 React.js 构建应用程序。除 auth 页面外,所有页面均正常工作。成功登录后,它应该将用户带到主页,但它已损坏,并显示空白页面。手动刷新后,开始显示主页。
当我通过 Chrome 浏览器中的开发工具检查应用程序时,它显示"Uncaught TypeError: destroy is not a function". 我附上了导致错误的代码。
...
const UnauthedWrapper = () => {
const navigate = useNavigate();
const location = useLocation();
const {
state: { auth, user },
} = useContext(AppContext);
useEffect(() => {
if (auth && user && user.emailVerified && user.dstoreName) {
navigate(`/app/overview`);
return null;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [auth, user]);
return (
<>
{!location.pathname.includes("/auth") ? (
<Header
logo="/images/logo.png"
page="landing"
hideLogin={process.env.REACT_APP_ENV === "PROD"}
/>
) : (
<Link to="/">
<img
src="/images/logo.png"
alt="logo"
className="logo ms-4 mt-4"
width={180}
/>
</Link>
)}
...
Run Code Online (Sandbox Code Playgroud)
cbe*_*tez 30
事实证明,当您尝试从useEffect钩子中返回非函数的任何内容时,这种情况几乎总是会发生。
如果您从 useEffect 函数返回任何内容,它必须是一个函数。
\nuseEffect(() => {\n if (auth && user && user.emailVerified && user.dstoreName) {\n navigate(`/app/overview`);\n return null;\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [auth, user]);\nRun Code Online (Sandbox Code Playgroud)\nuseEffect(() => {\n if (auth && user && user.emailVerified && user.dstoreName) {\n navigate(`/app/overview`);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [auth, user]);\nRun Code Online (Sandbox Code Playgroud)\nuseEffect(() => {\n if (auth && user && user.emailVerified && user.dstoreName) {\n navigate(`/app/overview`);\n return () => {}\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [auth, user]);\nRun Code Online (Sandbox Code Playgroud)\n
Hil*_*ory 30
就我而言,我将useEffect回调作为异步函数。
useEffect(async () =>{
// code here...
},[])
Run Code Online (Sandbox Code Playgroud)
所以我创建了一个独立的函数并在内部调用它useEffect。
const doSomething = async() =>{
// code here...
}
useEffect(() =>{
doSomething();
},[])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62805 次 |
| 最近记录: |