Use history.push in action creator with react-router-v4?

前端 未结 1 360
猫巷女王i
猫巷女王i 2020-12-01 18:18

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 p

相关标签:
1条回答
  • 2020-12-01 18:56

    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>
    

    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>.

    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');
            })
        }
    }
    
    0 讨论(0)
提交回复
热议问题