How to push to History in React Router v4?

后端 未结 21 1879
不思量自难忘°
不思量自难忘° 2020-11-22 00:27

In the current version of React Router (v3) I can accept a server response and use browserHistory.push to go to the appropriate response page. However, this isn

21条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 01:01

    I offer one more solution in case it is worthful for someone else.

    I have a history.js file where I have the following:

    import createHistory from 'history/createBrowserHistory'
    const history = createHistory()
    history.pushLater = (...args) => setImmediate(() => history.push(...args))
    export default history
    

    Next, on my Root where I define my router I use the following:

    import history from '../history'
    import { Provider } from 'react-redux'
    import { Router, Route, Switch } from 'react-router-dom'
    
    export default class Root extends React.Component {
      render() {
        return (
         
          
           
            ...
           
          
         
        )
       }
      }
    

    Finally, on my actions.js I import History and make use of pushLater

    import history from './history'
    export const login = createAction(
    ...
    history.pushLater({ pathname: PATH_REDIRECT_LOGIN })
    ...)
    

    This way, I can push to new actions after API calls.

    Hope it helps!

提交回复
热议问题