【问题标题】:React Router 4 How do I redirect programmatically inside a function? [duplicate]React Router 4 如何在函数内以编程方式重定向? [复制]
【发布时间】:2018-12-10 17:08:20
【问题描述】:

我有一个 singinUser 函数,当用户单击提交按钮时会调用该函数。我希望用户在获取数据完成后重定向到另一个 url。在之前的 react 版本中,我曾经使用来自 'react-router'browserHistory。 react-router 4应该怎么做?

import axios from 'axios';
    const ROOT_URL = 'http://localhost:3090';

    export const signinUser = ({ email, password }) => {
        return (dispatch) => {
            axios.post(`${ROOT_URL}/signin`, { email, password })
                .then(response =>{
                    //I want to redirect
                })
                .catch(err=>{

                })
        }
    }

【问题讨论】:

    标签: reactjs react-router react-redux


    【解决方案1】:

    这是我个人在我的应用程序中为受保护路由执行重定向的方式:

    const GuestRoute = ({ component: Component, ...rest }) => (
      <WebServiceContextConsumer>
        {
          context =>
            <Route
              {...rest}
              render={props =>
                context.auth.getUser() 
                  ? (<Redirect to={{pathname: "/", state: { from: props.location }}} />) 
                  : (<Component {...props} />)
              }
            />
        }
      </WebServiceContextConsumer>
    );
    

    您需要将视图与逻辑分开。执行您的任何调用,然后使用 Promise 捕获响应并在您的 View 组件中以您想要的方式处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-18
      • 2018-10-23
      • 1970-01-01
      • 2017-10-31
      • 2016-07-01
      • 2016-03-07
      • 2018-04-04
      • 2017-11-15
      相关资源
      最近更新 更多