How to push to History in React Router v4?

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

    According to React Router v4 documentation - Redux Deep Integration session

    Deep integration is needed to:

    "be able to navigate by dispatching actions"

    However, they recommend this approach as an alternative to the "deep integration":

    "Rather than dispatching actions to navigate you can pass the history object provided to route components to your actions and navigate with it there."

    So you can wrap your component with the withRouter high order component:

    export default withRouter(connect(null, { actionCreatorName })(ReactComponent));

    which will pass the history API to props. So you can call the action creator passing the history as a param. For example, inside your ReactComponent:

    onClick={() => {
      this.props.actionCreatorName(
        this.props.history,
        otherParams
      );
    }}
    

    Then, inside your actions/index.js:

    export function actionCreatorName(history, param) {
      return dispatch => {
        dispatch({
          type: SOME_ACTION,
          payload: param.data
        });
        history.push("/path");
      };
    }
    

提交回复
热议问题