React component communication routing parameter transfer (react-router-dom)

React component communication routing parameter transfer (react-router-dom)

I've been learning React recently, and now I'm using Vue at work. During the learning process, I compared the two to deepen my understanding.

The following is a small part of the knowledge points in react, which I personally think are also relatively common knowledge points. One of the ways for react components to communicate is routing parameter transmission (there are many ways for react components to communicate, such as props, event callbacks, context, router, redux, cache, etc.). Now single-page SPA is widely used. In order to jump to some pages without refreshing the entire page, it is inevitable to use routing jump. Then, in addition to jumping between pages, react routing also has a great function of passing parameters when switching pages or components, so as to achieve the purpose of communication.

Let's use a simple example to illustrate the way react routing jumps and passes parameters (this article focuses on the routing parameter passing method, and the routing configuration and related attributes are not expanded for the time being)

Preparation, install routing dependencies:

npm install -S react-router-dom

Then introduce the route into the page:

import Home from './component/ManageSystem';
import { BrowserRouter as Router } from 'react-router-dom'
function App() {
  return (
    <Router> //Route package, one or more pages in the home page may require route switching <div id="App">
        <Home />
      </div>
    </Router>
  );
}
 
export default App

A part of ManageSystem.js needs to switch the display content by routing. Route is the component that needs to be switched, path is the routing path, exact is the exact match, Link is the link, to represents the routing path of the jump, which corresponds to the path in Route, and Redirect is the redirection.

import React from 'react';
import Loadable from '../utils/loadable'
import {Route,Link,withRouter,Redirect,Switch} from "react-router-dom";
import { Button } from 'element-react';
//Dynamically load components to speed up the first screen rendering const About = Loadable(() => import('./About.js'))
const Users = Loadable(() => import('./Users.js'))
class Home extends React.Component {
    render() {
	    return (
		<div style={{ position: 'relative' }}>
		    <nav style={{ position: 'absolute', top: '0', left: '60%' }}>
				<ul>
				    <li style={{ marginBottom: '10px' }}>
				        <Link to={{pathname:"/home/about",query:{ text: '666' }}}>About</Link>
				    </li>
			        <li>
			            <Link to={{pathname:"/home/users/999",state:{ text: '888' }}}>Users</Link>
					</li>
				</ul>
			</nav>
			<div style={{ position: 'absolute', top: '20px', right: '20px' }}>
			    <Switch>
				    <Route exact path="/home" component={() => { return null }}>
				    </Route>
				    <Route exact path="/home/about" component={About}>
				    </Route>
				    <Route exact path="/home/users/:id" component={Users}>
				    </Route>
				    <Redirect exact from="/" to='/home' />
			    </Switch>
			</div>
		</div>
		);
	}
}
/*
The withRouter in the high-level component is used to wrap a component into the Route.
Then the three objects of react-router, history, location, and match, will be put into the props attribute of this component.
*/
export default withRouter(Home)

Here comes the point! ! !

When switching routes, there are three main ways to pass parameters: path dynamic path, query, and state

First, the path dynamic path method , when setting the path, a dynamic parameter is added to the address. The following dynamic parameters are: id

<Route exact path="/home/users/:id" component={Users}>
</Route>

When switching or jumping pages, put the information to be transmitted after the address, such as:

<Link to={{pathname:"/home/users/999"}}>Users</Link>

When switching to Users, you can use match to get the information passed by it. Users.js is as follows

import React from "react";
class Users extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      id: this.props.match.params.id //Get the information passed through the path dynamic parameter splicing here}
  }
  componentDidMount(){
    console.log(this.props,'users props')
  }
  render() {
    return (
      <div>
        <span>I am users: {this.state.id}</span>
      </div>
    )
  }
}
export default Users

Get: this.props.match.params.id

You can print props and check the contents. It is not difficult to find that the information exists in props

Then the corresponding programmatic jump is:

<button onClick={() => { this.props.history.push({ pathname: '/home/users/999' }) }}>about</button>
 
//Similarly, use this.props.match.params.id to get the value

The second parameter passing method is query , which passes information through the query parameter

<Link to={{pathname:"/home/users",query:{ text: '666' }}}>Users</Link>

Get: this.props.location.query.text

Likewise, print it out and see

The corresponding programmatic jump is:

<button onClick={() => { this.props.history.push({ pathname: '/home/users/999', query: { text: '666' } }) }}>Users</button>
 
//Similarly, get the method this.props.location.query.text

The third parameter passing method is state , which passes information through the parameter state. The usage is the same as query.

<Link to={{pathname:"/home/users",state:{ text: '666' }}}>Users</Link>

Get: this.props.location.state.text

Likewise, print it out and see

The corresponding programmatic jump is:

<button onClick={() => { this.props.history.push({ pathname: '/home/users/999', state: { text: '666' } }) }}>Users</button>
 
//Similarly, get the method this.props.location.state.text

ps: There is an important difference between query and state, that is, after the page jumps, when you refresh the current page, the query will disappear, but the state will not disappear, that is, it will still be saved in the location.

Let’s test it and modify the Users.js page. If the query does not exist, it will display “query has disappeared”.

import React from "react";
class Users extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text: this.props.location.query ? this.props.location.query.text : 'query has disappeared'
    }
  }
  componentDidMount(){
    console.log(this.props,'users props')
  }
  render() {
    return (
      <div>
        <span>I am users: {this.state.text}</span>
      </div>
    )
  }
}
export default Users

By jumping, the data is obtained normally and the query exists

Refresh the current page and the query disappears

The page displays

The same process uses the state parameter passing method. The state in the location will not disappear when the current page is refreshed. The state method is recommended.

Summary: This article mainly describes three ways of passing parameters in react routing jumps. If a page jump in a project requires passing certain information to the jump destination page, you may consider these methods. Difference: Although the dynamic address method is simple, the parameter passing method is single and can only be spelled in the address, and it is a string. When the transmitted information is too long, the address looks messy and the information will be exposed. For query, although the parameter passing method is the same as state, there is one thing: after jumping and refreshing the current page, the query will disappear, but the state will not.

Compare the routing parameter passing method in Vue:

Communication methods between Vue components (multiple scenarios, easy to understand, recommended for collection)

This is the end of this article about React component communication - routing parameter passing (react-router-dom). For more relevant React routing parameter passing content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on several ways to pass parameters in react routing
  • Detailed explanation of React routing parameter transfer method summary record

<<:  docker logs - view the implementation of docker container logs

>>:  HTML&CSS&JS compatibility tree (IE, Firefox, Chrome)

Recommend

The front-end must know how to lazy load images (three methods)

Table of contents 1. What is lazy loading? 2. Imp...

Introduction to the use of select optgroup tag in html

Occasionally, I need to group select contents. In ...

MySQL 5.7.19 installation and configuration method graphic tutorial (win10)

Detailed tutorial on downloading and installing M...

Vue/react single page application back without refresh solution

Table of contents introduction Why bother? Commun...

How to deploy redis in linux environment and install it in docker

Installation Steps 1. Install Redis Download the ...

WeChat applet implements simple calculator function

This article shares the specific code for the WeC...

Nginx uses the Gzip algorithm to compress messages

What is HTTP Compression Sometimes, relatively la...

Sample code for partitioning and formatting a disk larger than 20TB on centos6

1. Server environment configuration: 1. Check dis...

How to restore a single database or table in MySQL and possible pitfalls

Preface: The most commonly used MySQL logical bac...

Implementation of a simple login page for WeChat applet (with source code)

Table of contents 1. Picture above 2. User does n...

Example code for implementing verification code login in SMS API in Node

1. Node server setup + database connection The op...

Detailed explanation of CSS margin collapsing

Previous This is a classic old question. Since a ...

A brief discussion on the principle of Vue's two-way event binding v-model

Table of contents explain: Summarize Replenish Un...

Basic usage knowledge points of mini programs (very comprehensive, recommended!)

Table of contents What to do when registering an ...