反应路由器 - 登录后重定向 [英] react router - Redirection after login
问题描述
您能否帮助我理解我可以在最新版本的 react router ( v1.1.0 ) 中使用的重定向机制.我想根据 用户登录 的成功或失败重定向到 url
.我尝试执行以下操作首先创建一个历史使用.
Could you please help me in understanding the redirection mechanism I could use with latest version of react router ( v1.1.0 ) . I would like to redirect to a url
depending on the success or failure of user login .
I have tried to do the following
First created a history using.
let history = createBrowserHistory();
然后尝试使用
history.pushState(null, 'abc')
什么都没有发生.您能否告诉我进行转换的正确方法.从文档中我了解到 transitionTo()
API 在最新版本中不存在.如果您能指出一个简单的工作示例,那就太好了.
Nothing is happening. Could you please let me know the correct way to do transitions .From the docs I understood that transitionTo()
API is not present in the latest versions.
It will be great If you could point to a simple working example .
提前致谢.
推荐答案
想要更新这个线程,因为我花了很多时间来研究这个问题.在 React Router 2.0.x 中,不推荐使用 replaceState
以支持替换.详情请参见此处:https://github.com/ReactTraining/react-router/blob/v2.0.0/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors
Wanted to update this thread because I spent a good amount of time digging around on this. In React Router 2.0.x, replaceState
is deprecated in favor of replace. See here for details: https://github.com/ReactTraining/react-router/blob/v2.0.0/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors
正确的做法是这样的:
function requireAuth(nextState, replace) {
if (!userExists()) {
replace({
pathname: '/signin',
state: { nextPathname: nextState.location.pathname }
})
}
}
export const renderRoutes = () => (
<Router history={browserHistory}>
<Route path="protectedRoute" component={Protected} onEnter={requireAuth} />
<Route path="signin" component={SignIn} />
</Route>
</Router>
);
然后,在 SignIn 组件中,您可以像这样在成功登录后重定向:
Then, in the SignIn component, you can redirect after a successful sign in like this:
signInFunction({params}, (err, res) => {
// Now in the sign in callback
if (err)
alert("Please try again")
else {
const location = this.props.location
if (location.state && location.state.nextPathname) {
browserHistory.push(location.state.nextPathname)
} else {
browserHistory.push('/')
}
}
})
这篇关于反应路由器 - 登录后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!