javascript 如何在反应路由器中重置位置状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47512104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reset location state in react router
提问by sudheer singh
I am following react-router docs to create a protected route HOC and for unauthenticated requests I am Redirecting the user as following :
我正在按照 react-router 文档创建受保护的路由 HOC,对于未经身份验证的请求,我将用户重定向如下:
<Redirect to={{
pathname: '/input-number',
state: { from: props.location },
}} />
Now on the redirected component, I show an error message using the following logic :
现在在重定向的组件上,我使用以下逻辑显示错误消息:
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>
)
The problem is when the user reloads, the page the state associated with the location is not cleared and the error message is shown on each refresh once user has been redirected to the login component. I am looking for a way to clear the state. I think it must be possible without setting some app state.
问题是当用户重新加载时,与位置关联的页面没有清除,并且一旦用户被重定向到登录组件,每次刷新时都会显示错误消息。我正在寻找一种清除状态的方法。我认为不设置一些应用程序状态一定是可能的。
UPDATE :I am adding the complete PrivateRoute for clarity:
更新:为了清楚起见,我正在添加完整的 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 },
}}
/>
)
)}
/>);
}
`
`
回答by Robert Farley
When creating the historyobject for your <Router>during the initial setup of the React app, you could replace the state on the history's location with a state that does not include the fromprop.
在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 });
}
回答by Alexander Yamkov
Also, it is possible to replace the state without merging location it statys untouched:
此外,可以在不合并它保持不变的位置的情况下替换状态:
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 });
}

