2016-07-28 59 views
0

我想將用戶重定向到登錄頁面,它試圖訪問需要身份驗證的端點,但我想保存他們試圖訪問的頁面,以便一次他們登錄後,我可以將他們重定向到該頁面。在老版本的反應路由器的,我相信你能做到這一點,使用包裝(例如,從auth0拍攝):React路由器,如何保存轉換和成功登錄後重定向

export default (ComposedComponent) => { 
    return class AuthenticatedComponent extends React.Component { 

    static willTransitionTo(transition) { 
     // This method is called before transitioning to this component. If the user is not logged in, we’ll send him or her to the Login page. 
     if (!LoginStore.isLoggedIn()) { 
     transition.redirect('/login', {}, {'nextPath' : transition.path}); 
     } 
    } 

    ... 

    } 
} 

然後在得到在與API成功認證稱爲動作:

loginUser: (jwt) => { 
    var savedJwt = localStorage.getItem('jwt'); 

    AppDispatcher.dispatch({ 
     actionType: LOGIN_USER, 
     jwt: jwt 
    }); 

    if (savedJwt !== jwt) { 
     var nextPath = RouterContainer.get().getCurrentQuery().nextPath || '/'; 

     RouterContainer.get().transitionTo(nextPath); 
     localStorage.setItem('jwt', jwt); 
    } 
    } 

我知道,在新的反應路由器API,第一部分可以與

router.push({ pathname, query, state }) 

但是做,哪裏是訪問狀態的地方(在這種情況下,nextPath)?我相信路由器上的getCurrentQuery功能已被棄用

回答

0

在路由定義中使用onEnter掛鉤(demo)。

登錄頁面應該在道具中包含對路由器的引用(使用react-router withRouter HoC進行封裝)。此外,該位置支撐應包括所需要的數據,以回重定向到原來的位置:

const Login = withRouter(({ router, location }) => (
    <div> 
    <button type="click" onClick={() => { 
     LoginStore.logIn(); 
     router.replace(location.state); // on login redirect back to the original location, by taking that location's details from the router state 
     }}>Click to Login</button> 
    </div> 
)); 

的OnEnter處理程序的登錄應該重定向到登錄頁面,並通過在該位置的原始頁面的詳細信息(nextState)狀態:

const redirectToLogin = (nextState, replace) => { 
    if (!LoginStore.isLoggedIn()) { 
     const { pathname, search, query, state } = nextState.location; 
     replace({ pathname: '/login', state: { pathname, search, query, state } }); 
    } 
}; 

添加onEnter={ redirectToLogin }到需要登錄的路線:

ReactDOM.render((
    <Router> 
    <Route path="/" component={MainLayout}> 
     <IndexRoute component={Home} /> 
     <Route path="login" component={Login} /> 
     <Route path="page1" component={Page1} onEnter={ redirectToLogin } /> 
     <Route path="page2" component={Page2} onEnter={ redirectToLogin } /> 
    </Route> 
    </Router> 
), document.getElementById('root'))