登录后我必须重定向到/user/dashboard
页面,但每次我关闭选项卡并再次打开它时,它都会打开默认主页即/
。
import React from 'react';
import {isAuthenticated} from '../helpers/auth'
import {Route, Redirect } from 'react-router-dom';
const UserRoute = ({component: Component, ...rest}) => {
return(
<Route
{...rest}
render={(props)=>
isAuthenticated() && isAuthenticated().role === 0 ? (
<Component {...props} />
):(
<Redirect to="/signin" />
)
}
/>
);
}
导出默认UserRoute;
下面是一个通用的路由设置示例,它会检查"Public"one_answers"Private"和索引路径:
export default function Routes() {
function fromIndex() {
if (isAuthenticated) { // use your authentication mechanism
return '/user/dashboard'
}
return '/login'
}
return (
<Router history={history}> {/* history not required when using BrowserRouter */}
<Switch>
<Redirect exact from="/" to={fromIndex()} />
{/* publicPaths is an array of paths: [{...} */}
{publicPaths.map(item => (
<PublicRoute exact={item.exact} key={item.path} path={item.path}>
<item.component />
</PublicRoute>
))}
{privatePaths.map(item => (
<PrivateRoute exact={item.exact} key={item.path} path={item.path}>
<item.component />
</PrivateRoute>
))}
<NotFoundPage />
</Switch>
</Router>
)
}
在这里,PrivateRoute
是一个组件,它呈现children
,如果身份验证,否则重定向回'/login'。
PublicRoute
是一个组件,如果children
没有经过身份验证,则会重定向回"/"