How to push to History in React Router v4?

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

    Simplest way in React Router 4 is to use

    this.props.history.push('/new/url');
    

    But to use this method, your existing component should have access to history object. We can get access by

    1. If your component is linked to Route directly, then your component already has access to history object.

      eg:

      
      

      Here ViewProfile has access to history.

    2. If not connected to Route directly.

      eg:

       }
      

      Then we have to use withRouter, a heigher order fuction to warp the existing component.

      Inside ViewUsers component

      • import { withRouter } from 'react-router-dom';

      • export default withRouter(ViewUsers);

      That's it now, your ViewUsers component has access to history object.

    UPDATE

    2- in this scenario, pass all route props to your component, and then we can access this.props.history from the component even without a HOC

    eg:

     }
    

提交回复
热议问题