【发布时间】:2021-03-18 10:40:48
【问题描述】:
我正在尝试保护我的一些路由,因为您必须经过身份验证才能定向到该路由。我将我的路由包装在一个 routerWrapper 函数中,该函数进行一些验证,然后在验证后重定向到正确的路由。 我正在使用 useSelector 检查我的 authState,然后如果路由 isPrivate 和 isAuthenticated 我重定向到该路由,但毫无疑问地在第一个 React 渲染时我得到 isAuthenticated 为假,因此该函数正在返回登录路由。这是我的代码
const RouteWrapper = ({component, isPrivate, ...props}: IRoutProps) => {
//Add another property to check isAdmin
const state = useSelector((state: AppState) => state.auth);
const {isAuthenticated} = state;
console.log(isAuthenticated);
if (isPrivate) {
if (!state.isAuthenticated) {
console.log('Private');
return <Redirect to="/login" />;
} else {
return <Route {...props} component={component} />;
}
} else {
if (
props.path === '/login' &&
state.isAuthenticated === true &&
(state.user.type === 'Instructor' || state.user.type === 'Student')
) {
return <Redirect to="/" />;
} else if (
props.path === '/admin/login' &&
state.isAuthenticated &&
state.user.type === 'Admin'
) {
return <Redirect to="/admin/dashboard" />;
}
return <Route {...props} component={component} />;
}
};
【问题讨论】:
-
如果你在你的状态中添加一个
status可能是idle、authenticating、processed然后你检查状态是否仍在验证然后你不渲染登录组件?这就像有一个加载状态。 -
@MantasAstra 嘿,伙计,我没有完全理解这个想法,你能告诉我 if 条件是什么样的吗(我知道我必须向我的状态添加加载属性);
标签: reactjs react-redux react-router-dom