在 react-router-v4 中使用 history.push in action creator? [英] Use history.push in action creator with react-router-v4?

查看:20
本文介绍了在 react-router-v4 中使用 history.push in action creator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在不使用 react-router-reduxaction creator async action 完成路由的情况下解决这个问题的唯一工作方法是传递 history prop 从组件到动作创建者并执行:

The only working method that I found to work this out without using react-router-redux to route from action creator async action completion is by passing the history prop from the component to action creator and doing:

history.push('routename');

由于 BrowserRouter 忽略传递给它的 history 属性,因此我们不能使用带有 browserhistory 的自定义历史对象.

Since BrowserRouter ignores the history prop passed to it thus we cannot use custom history objects with browserhistory.

解决这个问题的最佳方法是什么?

What is the best possible way to work this out?

推荐答案

您可以使用带有自定义历史记录的 Router 代替 BrowserRouter

Instead of using BrowserRouter you could use the Router with custom history like

import { Router } from 'react-router'

import createBrowserHistory from 'history/createBrowserHistory'

export const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

在这种情况下,您的 history.push() 将起作用.使用 BrowserRouter history.push 不起作用,因为创建新的 browserHistory 不起作用,因为 创建了自己的历史实例,并听取有关的变化.因此,不同的实例将更改 url 但不会更新 <BrowserRouter>.

in which case your history.push() will work. With BrowserRouter history.push doesn't work because Creating a new browserHistory won't work because <BrowserRouter> creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the <BrowserRouter>.

一旦您创建了自定义history,您就可以将其导出,然后将其导入您的action creator 并使用它来动态导航

Once you create a custom history, you can export it and then import it in your action creator and use it to navigate dynamically like

import { history } from '/path/to/index';

const someAction = () => {
    return dispatch => {
        ApiCall().then((res) => {
            dispatch({type: 'SOME_CALL', payload: res })
            history.push('/home');
        })
    }
}

这篇关于在 react-router-v4 中使用 history.push in action creator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆