【发布时间】:2018-03-18 07:51:21
【问题描述】:
我正在尝试在使用 React Router v4 时实现一些服务器端身份验证(通过 xhr)。在我通过服务器验证用户已通过身份验证(通过拥有令牌)以及令牌存储在会话存储中(而不是这需要异步)之前,我不希望路由转换。
目前的问题是,即使用户未通过身份验证,我的“私人”路由仍在尝试呈现。
我的 React Router 路由如下所示:
class AppContainer extends Component {
render() {
return (
<div>
<main>
<Switch>
<Route exact path='/' component={Home} />
<PrivateRoute path='/dashboard' component={Dashboard} />
</Switch>
</main>
</div>
);
}
}
PrivateRoute,如指定的样子:
const isAuthenticated = async () => {
const resp = await axios.get('http://localhost/api/session');
const token = _.get(resp, 'data.success');
const authObj = storage.getFromSession('TOKEN');
return !_.isNil(_.get(authObj, 'Token')) && token;
};
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/',
state: { from: props.location }
}}/>
)
)}/>
)
export default PrivateRoute;
即使用户未通过身份验证,仪表板也会尝试呈现。我将如何等待我的 api 调用被返回,然后将用户重定向到 /dashboard 或 /(主页)?
【问题讨论】:
标签: reactjs react-router