sud*_*ngh 7 javascript reactjs react-router
我正在关注react-router文档来创建受保护的路由HOC,对于未经身份验证的请求,我将用户重定向如下:
<Redirect to={{
pathname: '/input-number',
state: { from: props.location },
}} />
Run Code Online (Sandbox Code Playgroud)
现在在重定向组件上,我使用以下逻辑显示错误消息:
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>
)
Run Code Online (Sandbox Code Playgroud)
问题是当用户重新加载时,页面与位置关联的状态不会被清除,并且一旦用户被重定向到登录组件,每次刷新时都会显示错误消息.我正在寻找一种清除状态的方法.我认为必须可以在不设置应用状态的情况下实现.
更新:为了清楚起见,我添加了完整的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 },
}}
/>
)
)}
/>);
}
Run Code Online (Sandbox Code Playgroud)
`
在React应用程序的初始设置期间history为您创建对象时<Router>,您可以将历史记录位置上的状态替换为不包含fromprop的状态.
const history = createHistory();
if (history.location && history.location.state && history.location.state.from) {
const state = { ...history.location.state };
delete state.from;
history.replace({ ...history.location, state });
}
Run Code Online (Sandbox Code Playgroud)
此外,可以在不合并未触及的位置的情况下替换状态:
const { state } = this.props.location;
if (state && state.copySurveyId) {
this.duplicateSurvey(state.copySurveyId);
const stateCopy = { ...state };
delete stateCopy.copySurveyId;
this.props.history.replace({ state: stateCopy });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8648 次 |
| 最近记录: |