我是React+Redux+Router的新手,我绞尽脑汁想如何在成功登录后将用户转发到PrivateRoute请求。
react认知触发COGNITO_LOGIN操作,并在成功登录时在商店中设置cognito.state = "LOGGED_IN"。我知道react路由器将请求的路由存储在location.state.from.pathname中,我知道要重定向BrowserRouter,我可以使用history.replace()。
我只是不知道我的代码到哪里去了,这样它就会在react onSubmit登录函数异步完成之后执行,因为这个包没有提供回调。
在我的登录表单组件中,我尝试了
componentWillReceiveProps(nextProps) {
if (nextProps.cognito.state === 'LOGGED_IN') {
// logged in, let's show redirect if any, or show home
try {
const { from } = this.props.location.state || {
from: { pathname: "/" }
};
nextProps.history.replace(from);
} catch (err) {
nextProps.history.replace("/");
}
}
}...but它执行得太早了。我不认为像这样的东西属于减速机,因为这些似乎只是为了直接操纵商店,但我可能会远离那里。
在react路由器-redux包中是否有一些功能可以在这里提供一些有用的东西?
我被困在没有回调的地方吗?有没有办法监视cognito.state的变化?
欢迎提出建议。
提亚
发布于 2018-01-15 06:51:13
使用react-router-v4进行重定向的标准方法是呈现一个负责重定向的<Redirect />。
就你而言:
render() {
if (this.props.cognito.state === 'LOGGED_IN') {
return (<Redirect to="/" />)
}
//...
}默认情况下,这将替换当前位置。
有关更多信息,请参见这示例。
发布于 2018-01-15 07:31:44
您可以在操作中使用push方法来分派一个操作,该操作将将应用程序重定向到所需的位置/路由。
action.js
import {push} from 'react-router-redux';
/*** write your API here and after success redirect your route ***/
.then(() => {
dispatch(push(args.redirectRoute))
})确保配置您的React路由器与Redux。
https://stackoverflow.com/questions/48257754
复制相似问题