gpt4 book ai didi

react-router - react 路由器-登录后重定向

转载 作者:行者123 更新时间:2023-12-03 11:32:02 25 4
gpt4 key购买 nike

您能否帮助我了解我可以在最新版本的 react router(v1.1.0)中使用的重定向机制。我想根据用户登录的成功或失败而重定向到url
我试图做以下
首先使用创建历史记录。

let history = createBrowserHistory();

然后尝试使用
history.pushState(null, 'abc')

没事您能否让我知道进行转换的正确方法。从文档中,我了解到 transitionTo() API在最新版本中不存在。
如果您可以指出一个简单的示例,那就太好了。

提前致谢。

最佳答案

想要更新此线程,因为我花了大量时间对此进行了深入研究。在React Router 2.0.x中,不赞成使用replaceState来代替replace。有关详细信息,请参见此处: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组件中,您可以在成功登录后重定向,如下所示:
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('/')
}
}
})

关于react-router - react 路由器-登录后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34119793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com