【发布时间】:2018-05-10 18:15:38
【问题描述】:
我正在关注 react-router 文档以创建受保护的路由 HOC,对于未经身份验证的请求,我将用户重定向如下:
<Redirect to={{
pathname: '/input-number',
state: { from: props.location },
}} />
现在在重定向组件上,我使用以下逻辑显示错误消息:
this.props.location.state && this.props.location.state.from &&
(
<Grid.Row>
<Grid.Column>
<Message negative>
<Message.Header>You must be logged in to visit the page</Message.Header>
</Message>
</Grid.Column>
</Grid.Row>
)
问题是当用户重新加载时,与位置关联的页面状态不会被清除,并且一旦用户被重定向到登录组件,每次刷新都会显示错误消息。我正在寻找一种清除状态的方法。我认为不设置一些应用状态一定是可能的。
更新:为了清楚起见,我添加了完整的 PrivateRoute:
`
export default function PrivateRoute({ component: Component, ...rest }) {
const isAuthenticated = localStorage.getItem(ACCESS_TOKEN);
return (
<Route
{...rest}
render={props => (
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/input-number',
state: { from: props.location },
}}
/>
)
)}
/>);
}
`
【问题讨论】:
标签: javascript reactjs react-router