【问题标题】:Use history.push in action creator with react-router-v4?在 react-router-v4 中使用 history.push in action creator?
【发布时间】:2018-07-08 22:42:30
【问题描述】:

我发现在不使用react-router-reduxaction creator async action 完成路由的情况下解决此问题的唯一工作方法是将组件中的history 道具传递给动作创建者并执行以下操作:

history.push('routename');

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

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

【问题讨论】:

    标签: reactjs redux react-router react-redux react-router-v4


    【解决方案1】:

    您可以使用带有自定义历史记录的Router,而不是使用BrowserRouter

    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 将不起作用,因为 &lt;BrowserRouter&gt; 创建了自己的历史实例,并监听其变化。所以不同的实例会改变 url 但不会更新&lt;BrowserRouter&gt;

    创建自定义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');
            })
        }
    }
    

    【讨论】:

    • history 还包含location (history.location.pathname),对于基于当前 url 的重定向非常有用。
    • 使用此解决方案,将历史对象导入动作创建者我收到错误TypeError: "_routing__WEBPACK_IMPORTED_MODULE_3__.default.push is not a function"
    • @ann.piv 你确定你已经默认导出了历史记录
    • 是的,它是默认导出。历史对象已导入操作文件中,但调用 history.push 时出现错误
    • @ann.piv 你能创建一个帖子,详细说明它的使用和创建吗
    猜你喜欢
    • 2018-01-21
    • 2018-06-08
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2017-09-02
    • 2017-08-02
    • 2018-02-20
    相关资源
    最近更新 更多