我想将用户重定向到他们尝试访问需要身份验证的端点的登录页面,但我想保存他们尝试访问的页面,这样一旦他们登录,我就可以将它们重定向到该页面。在旧版本的反应路由器中,我相信你能够使用包装器(取自auth0的例子)来做到这一点:
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 :(得分:0)
Login页面应包含对props中路由器的引用(用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>
));
login onEnter处理程序应重定向到Login页面,并在位置状态下传递原始页面详细信息(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'))