Tit*_*lum 19 javascript reactjs next.js next-router
我有一个自定义挂钩,它将检查您是否已登录,如果未登录,则将您重定向到登录页面。这是我的钩子的伪实现,假设您尚未登录:
import { useRouter } from 'next/router';
export default function useAuthentication() {
if (!AuthenticationStore.isLoggedIn()) {
const router = useRouter();
router.push('/login');
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我使用这个钩子时,我收到以下错误:
错误:找不到路由器实例。您应该只在应用程序的客户端内使用“next/router”。https://err.sh/vercel/next.js/no-router-instance
我检查了错误中的链接,但这并没有多大帮助,因为它只是告诉我将语句移至push渲染函数。
我也尝试过这个:
// My functional component
export default function SomeComponent() {
const router = useRouter();
useAuthentication(router);
return <>...</>
}
// My custom hook
export default function useAuthentication(router) {
if (!AuthenticationStore.isLoggedIn()) {
router.push('/login');
}
}
Run Code Online (Sandbox Code Playgroud)
但这只会导致同样的错误。
有什么方法可以允许在 Next.js 中的 React 组件之外进行路由吗?
jul*_*ves 14
发生错误的原因router.push是在页面首次加载的 SSR 期间在服务器上调用了 。一种可能的解决方法是扩展您的自定义挂钩以router.push在 auseEffect的回调内部调用,确保该操作仅发生在客户端上。
import { useEffect } from 'react';
import { useRouter } from 'next/router';
export default function useAuthentication() {
const router = useRouter();
useEffect(() => {
if (!AuthenticationStore.isLoggedIn()) {
router.push('/login');
}
}, [router]);
}
Run Code Online (Sandbox Code Playgroud)
然后在您的组件中使用它:
import useAuthentication from '../hooks/use-authentication' // Replace with your path to the hook
export default function SomeComponent() {
useAuthentication();
return <>...</>;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21535 次 |
| 最近记录: |