动作 redux 后反应路由器重定向

React router redirect after action redux

我正在使用 react-reduxreact-router。我需要在调度操作后重定向。

例如:我注册了几个步骤。行动后:

function registerStep1Success(object) {
    return {
        type: REGISTER_STEP1_SUCCESS,
        status: object.status
   };
}

我想重定向到带有 registrationStep2 的页面。我该怎么做?

p.s。在历史浏览器 '/registrationStep2' 还没有被访问过。结果注册Step1页面成功后才会出现此页面。

你检查过react-router-redux了吗?这个库使得将 react-router 与 redux 同步成为可能。

这是文档中的一个示例,说明如何使用 react-router-redux 的推送操作实现重定向。

import { routerMiddleware, push } from 'react-router-redux'

// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
  reducers,
  applyMiddleware(middleware)
)

// Dispatch from anywhere like normal.
store.dispatch(push('/foo'))

使用 React Router 2+,无论您在何处调度操作,您都可以调用 browserHistory.push()(或 hashHistory.push(),如果您使用的是

):

import { browserHistory } from 'react-router'

// ...
this.props.dispatch(registerStep1Success())
browserHistory.push('/registrationStep2')

如果您使用的是异步动作创建器,您也可以这样做。

以 Eni Arinde 之前的回答为基础(我没有发表评论的名誉),这里是如何在异步操作后使用 store.dispatch 方法:

export function myAction(data) {
    return (dispatch) => {
        dispatch({
            type: ACTION_TYPE,
            data,
        }).then((response) => {
            dispatch(push('/my_url'));
        });
    };
}

诀窍是在操作文件中而不是在 reducer 中执行此操作,因为 reducer 不应该有副作用。

您可以使用来自 'react-router-dom'

的 {withRouter}

下面的示例演示了对推送的调度

export const registerUser = (userData, history) => {
  return dispatch => {
    axios
    .post('/api/users/register', userData)
    .then(response => history.push('/login'))
    .catch(err => dispatch(getErrors(err.response.data)));
  }
}

历史参数在组件中作为第二个参数分配给动作创建者(在本例中 'registerUser')

signup = e => {
  e.preventDefault();
  const { username, fullname, email, password } = e.target.elements,
    { dispatch, history } = this.props,
    payload = {
      username: username.value,
      //...<payload> details here
    };
  dispatch(userSignup(payload, history));
  // then in the actions use history.push('/<route>') after actions or promises resolved.
};

render() {
  return (
    <SignupForm onSubmit={this.signup} />
    //... more <jsx/>
  )
}

路由器版本 4+ 的最简单解决方案: 我们使用 "react-router-dom": "4.3.1" 它不适用于版本 5+

从初始化位置导出您的浏览器历史记录 并使用 browserHistory.push('/pathToRedirect'):

必须安装包历史(例如:“history”:“4.7.2”):

npm install --save history

在我的项目中,我在 index.js:

中初始化浏览器历史记录
import { createBrowserHistory } from 'history';

export const browserHistory = createBrowserHistory();

在操作中重定向:

export const actionName = () => (dispatch) => {
    axios
            .post('URL', {body})
            .then(response => {
                // Process success code
                  dispatch(
                    {
                      type: ACTION_TYPE_NAME,
                      payload: payload
                    }
                  );
                }
            })
            .then(() => {
                browserHistory.push('/pathToRedirect')
            })
            .catch(err => {
                // Process error code
                    }
                );
            });
};

这是路由应用

的工作copy
    import {history, config} from '../../utils'
        import React, { Component } from 'react'
        import { Provider } from 'react-redux'
        import { createStore, applyMiddleware } from 'redux'
        import Login from './components/Login/Login';
        import Home from './components/Home/Home';
        import reducers from './reducers'
        import thunk from 'redux-thunk'

        import {Router, Route} from 'react-router-dom'

        import { history } from './utils';

        const store = createStore(reducers, applyMiddleware(thunk))



        export default class App extends Component {
          constructor(props) {
            super(props);

            history.listen((location, action) => {
              // clear alert on location change
              //dispatch(alertActions.clear());
            });
          }
          render() {
            return (
              <Provider store={store}>
                <Router history={history}>
                  <div>
                    <Route exact path="/" component={Home} />
                    <Route path="/login" component={Login} />
                  </div>
                </Router>
              </Provider>
            );
          }
        }

export const config = {
    apiUrl: 'http://localhost:61439/api'
};
import { createBrowserHistory } from 'history';

    export const history = createBrowserHistory();
//index.js
export * from './config';
export * from './history';
export * from './Base64';
export * from './authHeader';

import { SHOW_LOADER, AUTH_LOGIN, AUTH_FAIL, ERROR, AuthConstants } from './action_types'

import Base64 from "../utils/Base64";

import axios from 'axios';
import {history, config, authHeader} from '../utils'
import axiosWithSecurityTokens from '../utils/setAuthToken'


export function SingIn(username, password){


    return async (dispatch) => {
      if(username == "gmail"){
        onSuccess({username:"Gmail"}, dispatch);
      }else{
      dispatch({type:SHOW_LOADER, payload:true})
        let auth = {
            headers: {
              Authorization: 'Bearer ' + Base64.btoa(username + ":" + password)
            }
          }
        const result = await axios.post(config.apiUrl + "/Auth/Authenticate", {}, auth);
        localStorage.setItem('user', result.data)
        onSuccess(result.data, dispatch);
    }
  }

}

export function GetUsers(){
  return async (dispatch) => {
var access_token = localStorage.getItem('userToken');
    axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}` 

    var auth = {
      headers: authHeader()
    }
    debugger
      const result = await axios.get(config.apiUrl + "/Values", auth);
      onSuccess(result, dispatch);
      dispatch({type:AuthConstants.GETALL_REQUEST, payload:result.data})
  }
}



const onSuccess = (data, dispatch) => {

  const {username} = data;
  //console.log(response);
  if(username){
    dispatch({type:AuthConstants.LOGIN_SUCCESS, payload: {Username:username }});
    history.push('/');
    // Actions.DashboardPage();
  }else{
    dispatch({ type: AUTH_FAIL, payload: "Kullanici bilgileri bulunamadi" });
  }
  dispatch({ type: SHOW_LOADER, payload: false });
}
const onError = (err, dispatch) => {
  dispatch({ type: ERROR, payload: err.response.data });
  dispatch({ type: SHOW_LOADER, payload: false });
}

export const SingInWithGmail = () => {
  return { type :AuthConstants.LOGIN_SUCCESS}
}

export const SignOutGmail = () => {
  return { type :AuthConstants.LOGOUT}
}

使用钩子的更新答案;对于路由器 v5 用户。

Working on react-router-dom:5.1.2.

No installation of external package is required.

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

您可以像以前一样使用 history

更多详细信息和 API - 阅读 manual

我们可以使用“connected-react-router”。

    import axios from "axios";
    import { push } from "connected-react-router";
    
    export myFunction = () => {
      return async (dispatch) => {
        try {
          dispatch({ type: "GET_DATA_REQUEST" });
          const { data } = await axios.get("URL");
          dispatch({
            type: "GET_DATA_SUCCESS",
            payload: data
          });
        } catch (error) {
          dispatch({
            type: "GET_DATA_FAIL",
            payload: error,
          });
          dispatch(push("/notfound"));
        }
      };
    };

注意——请先到https://github.com/supasate/connected-react-router阅读文档并设置connected-react-router,然后使用connected-react-router中的“push”。

在使用 react-router-dom 版本 +5 时,您不能在 redux(redux 工具包)中使用 useHistory 挂钩。

因此,如果您想 在调度操作后重定向,您可以在当前页面(组件)中“通过 useHistory() 挂钩”获取历史记录,然后传递历史记录将您的有效负载作为 redux 的参数。 因此,您可以在像这样发送操作后轻松地在 redux 中管理您的历史记录: history.push(“某处)