React learning notes -- route dom of component communication

Keywords: Front-end React

  Recently, in the study of react, vue is used in our work. In the process of learning, we compare the two to deepen our understanding.

  The following is a small part of the knowledge points in react, which I personally think is also a common knowledge point. One of the ways of react component communication - routing parameters (there are many ways of react component communication, such as props, event callback, context, router, redux, cache, etc.). At present, single page SPA is widely used. It is inevitable to use route jump without refreshing the whole page to jump some pages. In addition to jumping between pages, react route also plays a great role in passing parameters during page or component switching, so as to achieve the purpose of communication.

  Let's use a simple example to illustrate the method of parameter transfer of react route jump (this paper focuses on the method of route parameter transfer, route configuration and related attributes, which will not be expanded temporarily)

  Prepare to install routing dependencies:

npm install -S react-router-dom

  Then introduce the route in the page:

import Home from './component/ManageSystem';
import { BrowserRouter as Router } from 'react-router-dom'
function App() {
  return (
    <Router>               //Route packages. One or more pages on the front page may need route switching
      <div id="App">
        <Home />
      </div>
    </Router>
  );
}

export default App

Some part of ManageSystem.js needs route switching display content. Route is the component to be switched, path is the route path, exact is the exact match, Link is the Link, to represents the jump route path, which corresponds to the path in route, and Redirect is 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>
		);
	}
}
/*
withRouter in high-order components is used to wrap a component into the Route,
Then the three objects history, location and match of the react router will be put into the props attribute of the component.
*/
export default withRouter(Home)

  Here comes the point!!!

  When switching routes, there are three main parameter transmission methods: path, dynamic path, query and state  

  First, the path dynamic path method. When setting the path, splice a dynamic parameter in the address. The following dynamic parameter is: id

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

During page switching or jump, spell the information to be transmitted behind the address, such as:

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

When you switch to users, you can get the information from users through match. 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  //Here you can get the information passed through the path dynamic parameter splicing
    }
  }
  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 this 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 parameter query

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

Get: this.props.location.query.text

Similarly, print it out

  The corresponding programmed jump is:

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

//Similarly, the access method is this.props.location.query.text

The third parameter passing method is state. The information is passed through the parameter state. The usage is consistent with query

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

Get: this.props.location.state.text

Similarly, print it out

  The corresponding programmed jump is:

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

//Similarly, the access method is this.props.location.state.text

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

You might as well 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 Disappeared'
    }
  }
  componentDidMount(){
    console.log(this.props,'users props')
  }
  render() {
    return (
      <div>
        <span>I am users: {this.state.text}</span>
      </div>
    )
  }
}
export default Users

Through the jump, the data obtained is normal, and the query exists

 

  Refresh the current page again, and the query disappears

  The page is displayed as

  The same process uses the state parameter passing method, and the state refresh of the current page in the location will not disappear. The state method is recommended.

Summary: This paper mainly describes three ways to transfer parameters in react route jump. When a page Jump is involved in the project, some information needs to be transferred to the jump destination page. You may wish to consider these ways. Difference: Although the dynamic address method is simple, the parameter transmission method is single. It can only be spelled in the address and 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 transfer method is consistent with state, there is one point. After the jump, refresh the current page, query will disappear, but state will not.

Compare the parameter transmission methods in Vue:

Communication mode between Vue components (various scenarios, easy to understand, recommended Collection)_ Front end dish Xiaobai leo's blog - CSDN blog

Posted by punked on Sat, 23 Oct 2021 22:03:53 -0700