How to push to History in React Router v4?

后端 未结 21 1855
不思量自难忘°
不思量自难忘° 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:23

    Here's my hack (this is my root-level file, with a little redux mixed in there - though I'm not using react-router-redux):

    const store = configureStore()
    const customHistory = createBrowserHistory({
      basename: config.urlBasename || ''
    })
    
    ReactDOM.render(
      
        
           {
            window.appHistory = history
            return (
              
            )
          }}/>
        
      ,
      document.getElementById('root')
    )
    

    I can then use window.appHistory.push() anywhere I want (for example, in my redux store functions/thunks/sagas, etc) I had hoped I could just use window.customHistory.push() but for some reason react-router never seemed to update even though the url changed. But this way I have the EXACT instance react-router uses. I don't love putting stuff in the global scope, and this is one of the few things I'd do that with. But it's better than any other alternative I've seen IMO.

提交回复
热议问题