How to push to History in React Router v4?

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

    Nasty question, took me quite a lot of time, but eventually, I solved it this way:

    Wrap your container with withRouter and pass history to your action in mapDispatchToProps function. In action use history.push('/url') to navigate.

    Action:

    export function saveData(history, data) {
      fetch.post('/save', data)
         .then((response) => {
           ...
           history.push('/url');
         })
    };
    

    Container:

    import { withRouter } from 'react-router-dom';
    ...
    const mapDispatchToProps = (dispatch, ownProps) => {
      return {
        save: (data) => dispatch(saveData(ownProps.history, data))}
    };
    export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Container));
    

    This is valid for React Router v4.x.

提交回复
热议问题