79

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

例如:我已经注册了几步。行动后:

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

我想使用registrationStep2重定向到页面。我怎样才能做到这一点?

ps 在历史浏览器中'/registrationStep2' 没有被访问过。该页面只有在结果注册成功后才会出现Step1页面。

4

10 回答 10

67

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

import { browserHistory } from 'react-router'

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

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

于 2016-03-01T12:51:00.070 回答
26

你检查过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'))
于 2016-03-01T00:10:18.363 回答
8

路由器版本 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
                    }
                );
            });
};
于 2019-04-23T14:26:41.160 回答
5

为了建立 Eni Arinde 先前的答案(我没有评论的声誉),这里是如何store.dispatch在异步操作之后使用该方法:

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

诀窍是在动作文件中而不是在减速器中进行,因为减速器不应该有副作用。

于 2017-07-28T07:57:03.613 回答
3

我们可以使用“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首先设置,然后使用“push” from connected-react-router.

于 2021-02-04T04:03:53.413 回答
3

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

工作react-router-dom:5.1.2

无需安装外部软件包。

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 - 阅读手册

于 2020-06-23T11:02:05.520 回答
2

您可以使用“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”)

于 2018-04-20T00:49:24.210 回答
0
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/>
  )
}
于 2018-07-12T10:16:23.433 回答
0

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

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

于 2021-12-08T12:06:21.083 回答
0

这是路由应用程序的工作副本

    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}
}
于 2019-06-26T09:34:15.533 回答