react-cognito和路由器v4:登录后将用户重定向到请求的PrivateRoute

时间:2018-01-15 06:09:31

标签: reactjs redux amazon-cognito react-router-v4

我是React + Redux +路由器的新手,我正在摸索如何在成功登录后将用户转发到所请求的PrivateRoute。

react-cognito会在成功登录时触发COGNITO_LOGIN操作并在商店中设置cognito.state = "LOGGED_IN"。我知道react-router在location.state.from.pathname中存储了请求的路由,我知道要重定向BrowserRouter,我可以使用history.replace()

我只是不知道我的代码在哪里,以便在react-cognito 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("/");
      }
    }
  }

......但执行得太早了。我不认为这样的东西属于reducer,因为这些似乎只是为了直接操作商店,但我可能会离开那里。

react-router-redux包中是否有一些功能可以提供一些有用的功能?

我没有回电就陷入了困境?有没有办法观察cognito.state的变化?

建议欢迎。

TIA

2 个答案:

答案 0 :(得分:0)

使用react-router-v4执行此操作的标准方法是呈现<Redirect />来处理重定向。

在你的情况下:

render() {
    if (this.props.cognito.state === 'LOGGED_IN') {
        return (<Redirect to="/" />)
    }
    //...
}

默认情况下会替换当前位置。

有关详细信息,请参阅this示例。

答案 1 :(得分:0)

您可以在操作中使用push方法发送操作,将您的应用重定向到所需的位置/路线。

  

action.js

import {push} from 'react-router-redux';

/*** write your API here and after success redirect your route ***/

.then(() => {
   dispatch(push(args.redirectRoute))
 })

确保使用 Redux configured React Router