How to push to History in React Router v4?

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

    Create a custom Router with its own browserHistory:

    import React from 'react';
    import { Router } from 'react-router-dom';
    import { createBrowserHistory } from 'history';
    
    export const history = createBrowserHistory();
    
    const ExtBrowserRouter = ({children}) => (
      
      { children }
      
    );
    
    export default ExtBrowserRouter
    

    Next, on your Root where you define your Router, use the following:

    import React from 'react';       
    import { /*BrowserRouter,*/ Route, Switch, Redirect } from 'react-router-dom';
    
    //Use 'ExtBrowserRouter' instead of 'BrowserRouter'
    import ExtBrowserRouter from './ExtBrowserRouter'; 
    ...
    
    export default class Root extends React.Component {
      render() {
        return (
          
            
              
                ...
                
                ...
              
            
          
        )
      }
    }
    

    Finally, import history where you need it and use it:

    import { history } from '../routers/ExtBrowserRouter';
    ...
    
    export function logout(){
      clearTokens();      
      history.push('/login'); //WORKS AS EXPECTED!
      return Promise.reject('Refresh token has expired');
    }
    

提交回复
热议问题