专用路由不会重定向到登录页面



我有一个简单的应用程序:

const App = () => (
<div className="App">
<Router>
<NavBar />
<RenderRoutes />
</Router>
</div>
);

将配置路由为单独的对象:

import { Home } from '../Components/Home';
import { Login } from '../Components/Login';
import { Test } from '../Components/Test';
export const routes = [
{
path: '/',
key: 'root',
component: Home,
exact: true,
},

{
path: '/test',
key: 'test',
component: Test,
exact: true,
},
{
path: '/login',
key: 'login',
component: Login,
exact: true,
},
]

RenderRoutes(路由从路由配置文件导入(:

export const RenderRoutes = () => {  
return (
<Switch>      
{routes.map((route) => {          
return <PrivateRoute key={route.key} {...route}  />
})}
<Route component={Error404} />
</Switch>
)
}

我的PrivateRoute组件如下所示:

export const PrivateRoute = ({ children, ...rest }) => {
const isAuthenticated = false;
return (
<Route {...rest} render={() => {
return isAuthenticated === true
? children
: <Redirect to='/login' />
}} />
)
}

但是私有路由总是呈现子代,无论是Authenticated===true还是false,为什么?

您已将isAuthenticated定义为PrivateRoute组件中的常量变量,值为false,因此它绑定为始终呈现子级。

您的isAuthenticated值应该可以从道具或上下文中获得,也可以从存储身份验证状态的redux存储中获得。

export const PrivateRoute = ({ children,isAuthenticated, ...rest }) => {
return (
<Route {...rest} render={() => {
return isAuthenticated === true
? children
: <Redirect to='/login' />
}} />
)
}

还要注意,如果isAuthenticated值是异步填充的,那么您还应该有一个加载状态来考虑计算延迟,否则即使身份验证请求成功,您也会被重定向到登录。

最新更新