NPM install react-router-dom

As mentioned in the last article, react routing is quite different from other frameworks, and when I tried to jump directly to JS, I found that there was a lot of work to do.

WithRouter is the main character:

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

This method converts a non-routable component into a routable component. You can use this. Props to obtain the methods for using history, location, and match

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

class Demo extends React.Component {
  constructor(props) {
    super(props);
  }

  goBack1() {
    this.props.history.goBack();
  }

  goBack2() {
    this.props.history.go(-1);
  }
  
  goto() {
    this.props.history.push('/url');
  }

  render() {
    return (
      <div style={{margin: '20px'}} > < button onClick = {() = > enclosing goBack1 ()} > back 1 < / button > < button onClick = {() = > enclosing goBack2 ()} > back 2 < / button > < button OnClick = {() = > this. Goto ()} > redirect to URL < / button > < / div >)}}export default withRouter(Demo);
Copy the code

When the ‘Demo’ component is exposed, wrap it with withRouter, and the ‘Demo’ component’s this will load the history, location, and match methods for use.

Let me talk about the three ways of routing parameters

Method 1: Through Params

<Route path='/demo/:id' compontent={test}></Route>

<Link to='/demo/2'>test</Link>

this.props.history.push('/demo/2') this. Props. Match. Params. Id / / to get id: 2Copy the code

Method 2: Query

<Link to={ pathname: ' /demo' , query : { name: 'Two hundred pounds' }}>

this.props.history.push({
    pathname: '/demo',
    query: {
        name: 'Two hundred pounds'}}) enclosing props. Location. Query. Name / / to get name: two hundred cattiesCopy the code

Mode 3: Use state

<Link to={ pathname: ' /demo' , state : { name: 'Two hundred pounds' }}>

this.props.history.push({
    pathname: '/demo',
    state: {
        name: 'Two hundred pounds'}}) enclosing props. The location. The state. The name / / to get name: two hundred cattiesCopy the code

* Query and state are basically the same, state has more encryption than query, but there is no related example, hope you can add it.