使用react.push in action creator with react-router-v4?

Jit*_*ani 19 reactjs react-router redux react-redux react-router-v4

我发现没有使用完成react-router-redux路由的唯一工作方法action creator async action是将historyprop从组件传递给action creator并执行:

history.push('routename');
Run Code Online (Sandbox Code Playgroud)

由于BrowserRouter忽略了传递给它的历史道具,因此我们不能将自定义历史对象与browserhistory一起使用.

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

Shu*_*tri 28

而不是使用BrowserRouter你可以使用Router自定义历史记录

import { Router } from 'react-router'

import createBrowserHistory from 'history/createBrowserHistory'

export const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你的history.push()工作.使用BrowserRouter history.push不起作用,因为创建新的browserHistory将无法工作,因为<BrowserRouter>创建自己的历史记录实例,并侦听其中的更改.因此,不同的实例将更改URL但不更新<BrowserRouter>.

创建自定义后history,您可以将其导出然后导入到自定义中action creator并使用它进行动态导航

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

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