【问题标题】:how to reset react-router on page reload如何在页面重新加载时重置反应路由器
【发布时间】:2017-02-24 01:21:42
【问题描述】:

使用“反应路由器”:“^3.0.2”,

当我重新加载页面时,我需要它转到当前正在执行的默认视图。但是,历史中的实际路线仍然与我刷新时的路线相同。因此,该组件在不应该重新安装时重新安装。

路由历史

    export const browserHistory = useRouterHistory(useBeforeUnload(createHistory))()

路线

 <Router history={browserHistory}>
    <Route path='/' name='Auth' component={Auth}>
      <IndexRoute
        component={Dashboard}
        onEnter={(nextState, replace) => replace('/login')} />
      <Route path='dashboard' name='Dashboard' component={Dashboard} />
      <Route path='resources' name='Resources' component={Resources} />
      <Route path='users' name='Users' component={UsersContainer} />
      <Route path='user/:params' name='User' component={UserContainer} />
    </Route>
    <Route path='/' name='NoAuth' component={NoAuth}>
      <Route path='login' name='Login Page' component={Login} />
    </Route>
  </Router>

这是我检查用户是否仍有有效会话令牌的方式,以及我重新路由到仪表板的方式。不确定我这样做是否是最好的方法。

    const _checkAuth = () => {
  if (profile) {
    const res = JSON.parse(profile)
    store.dispatch({ type: types.LOGIN_IDENTITY_SUCCESS, res })
    console.log(browserHistory.getCurrentLocation().pathname)
    router.replace('/dashboard')
  }
}

_checkAuth()

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    如果您想使用 react-router 推送到新路由,您可以使用 .push 方法将另一条路由推送到堆栈上,如果您正在寻找,这不会删除历史中的第一条路由,但它会正确地将新路由推送到 react-router

    const _checkAuth = () => {
      if (profile) {
        const res = JSON.parse(profile)
        store.dispatch({ type: types.LOGIN_IDENTITY_SUCCESS, res })
        console.log(browserHistory.getCurrentLocation().pathname)
        browserHistory.push('/dashboard');
      }
    }
    
    _checkAuth()
    

    只需将router.replace('/dashboard') 替换为browserHistory.push('/dashboard')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 2019-10-21
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      相关资源
      最近更新 更多