小编典典

使用带有action-router-v4的动作创建者中的history.push吗?

reactjs

我发现无需使用完成react-router-redux路线即可解决此问题的唯一工作方法action creator async action是将history道具从组件传递给动作创建者,然后执行以下操作:

history.push('routename');

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

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


阅读 307

收藏
2020-07-22

共1个答案

小编典典

除了使用之外,BrowserRouter您可以使用Router带有自定义历史记录的

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无效,因为<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');
        })
    }
}
2020-07-22