受保护路由- react-router-dom v6



我遵循这个实现受保护的路由,然而,我得到一个非常奇怪的错误。

根据我写条件的方式,组件不会被重新渲染。下面是代码:

export const LoginRequired = ({ isAuthenticated, children }) => {
if (isAuthenticated) {
return <Navigate to='/' replace /> // isAuthenticated state changes detected
// return children <- isAuthenticated state changes not detected
}
// return <Navigate to='/' replace /> <- isAuthenticated state changes not detected
return children; // isAuthenticated state changes detected
}

如果isAuthenticated为真,我希望渲染子节点。然而,当我没有注释代码块时,状态变化不会被检测到。

我不太确定为什么这是不工作,因为我有完全相同的代码为不同的路由。

export const ProtectedRoute = ({ isAuthenticated, children }) => {
if (isAuthenticated) {
return <Navigate to='/' replace />
}
return children;
}

我错过了什么吗?

谢谢。

您遇到的问题是您需要在isAuthenticated变量前面添加一个not(!)操作符。

我还建议修改导航组件,使用useNavigation钩子代替。这通常是首选,除非在类组件中不能使用钩子。

export const ProtectedRoute = ({ isAuthenticated, children }) => {
const navigate = useNavigate();
if (!isAuthenticated) { //Check not authenticated
navigate("/", { replace: true });
}
return children;
}

最新更新