How to push to History in React Router v4?

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

    You can use the history methods outside of your components. Try by the following way.

    First, create a history object used the history package:

    // src/history.js
    
    import { createBrowserHistory } from 'history';
    
    export default createBrowserHistory();
    

    Then wrap it in (please note, you should use import { Router } instead of import { BrowserRouter as Router }):

    // src/index.jsx
    
    // ...
    import { Router, Route, Link } from 'react-router-dom';
    import history from './history';
    
    ReactDOM.render(
      
        
          
    • Home
    • Login
    , document.getElementById('root'), );

    Change your current location from any place, for example:

    // src/actions/userActionCreators.js
    
    // ...
    import history from '../history';
    
    export function login(credentials) {
      return function (dispatch) {
        return loginRemotely(credentials)
          .then((response) => {
            // ...
            history.push('/');
          });
      };
    }
    

    UPD: You can also see a slightly different example in React Router FAQ.

提交回复
热议问题