我正在尝试从其状态驱动我的应用程序的导航。这是我的用例:
Given the user is on the Login page
When the application state changes to isLoggedIn
Then the application should navigate to the Dashboard page
这是我目前的实施方式:
if (browserHistory.getCurrentLocation().pathname === '/login' && store.isLoggedIn) {
browserHistory.push('/dashboard');
}
不幸的是,通过react-router文档和问题,我知道browserHistory.getCurrentLocation()
不是官方API,不应该使用它。有推荐的方法吗?
P.S。此代码在React组件外部运行,因此我无法使用this.props.location.pathname
答案 0 :(得分: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('/');
}
};