如何从react-router获取当前位置?

Nar*_*esh 6 reactjs react-router

我试图从其状态驱动我的应用程序的导航.这是我的用例:

Given the user is on the Login page
When the application state changes to isLoggedIn
Then the application should navigate to the Dashboard page
Run Code Online (Sandbox Code Playgroud)

这是我当前的实现有效:

if (browserHistory.getCurrentLocation().pathname === '/login' && store.isLoggedIn) {
    browserHistory.push('/dashboard');
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,通过react-router文档和问题,我知道这browserHistory.getCurrentLocation()不是官方API,不应该使用它.有推荐的方法吗?

PS此代码在React组件外部运行,因此我无法使用 this.props.location.pathname

小智 0

export const onAuthChange = (isAuthenticated) => {
  const pathname = browserHistory.getCurrentLocation().pathname;
  const isUnauthenticatedPage = unauthenticatedPages.includes(pathname);
  const isAuthenticatedPage = authenticatedPages.includes(pathname);

  if (isUnauthenticatedPage && isAuthenticated) {
    browserHistory.replace('/Dashboard');
  } else if (isAuthenticatedPage && !isAuthenticated) {
    browserHistory.replace('/');
  }

};
Run Code Online (Sandbox Code Playgroud)

  • 如果您解释您的答案,通常对其他用户很有用。将来您的答案可能会以意想不到的方式帮助其他人,但如果它只是一段代码,这种可能性就较小。 (2认同)