【问题标题】:How to reset location state in react router如何在反应路由器中重置位置状态
【发布时间】: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


    【解决方案1】:

    在 React 应用的初始设置期间为您的 &lt;Router&gt; 创建 history 对象时,您可以将历史记录位置上的状态替换为不包含 from 属性的状态。

    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 });
    }
    

    【讨论】:

    • 但是 history.replace 会刷新页面。不刷新页面可以吗?
    【解决方案2】:

    此外,可以在不合并未触及的位置的情况下替换状态:

    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 });
    }
    

    【讨论】:

      【解决方案3】:

      这可能不是最理想的方法,但在我的情况下,最简单的处理方法是使用 history.replace() 并用相同的 URL 替换当前 URL,但省略 location 位置状态对象(也应该适用于参数) .但是,您必须小心,并且仅在您使用了位置状态对象或参数的值之后才替换 URL。就我而言:

      // 应用程序中的某个位置:

          history.push("to/app/route", {
            contentOfLocationState: true
          });
      

      //在映射到上述路由的组件中

      function (){
          try {
            // Post to API
            Post(...{ contentOfLocationState });
          } catch (e) {
            // error
          } finally {
            history.replace("to/app/route");
          }
      

      PS:使用@robert-farley 描述的技术,react router 将开始起作用并为我显示白屏。不过可能是我的设置有问题

      【讨论】:

        猜你喜欢
        • 2021-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2020-10-18
        • 2021-11-12
        • 2017-03-23
        相关资源
        最近更新 更多