How to push to History in React Router v4?

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

    If you are using Redux, then I would recommend using npm package react-router-redux. It allows you to dispatch Redux store navigation actions.

    You have to create store as described in their Readme file.

    The easiest use case:

    import { push } from 'react-router-redux'
    
    this.props.dispatch(push('/second page'));
    

    Second use case with Container/Component:

    Container:

    import { connect } from 'react-redux';
    import { push } from 'react-router-redux';
    
    import Form from '../components/Form';
    
    const mapDispatchToProps = dispatch => ({
      changeUrl: url => dispatch(push(url)),
    });
    
    export default connect(null, mapDispatchToProps)(Form);
    

    Component:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types';
    
    export default class Form extends Component {
      handleClick = () => {
        this.props.changeUrl('/secondPage');
      };
    
      render() {
        return (
          
    Readme file ); } }

提交回复
热议问题