SoFunction
Updated on 2025-04-07

Hand in hand to learn how to use React

Hand in hand, take you to learn React three steps, learn how to use it, and start creating your own React project

What is React-router

React Router is a powerful routing library based on React, which allows you to quickly add views and data streams to your app while keeping pages and URLs synchronized. To be simple, it helps our program display different content in different URLs.

Why use React-router

When we develop, it is impossible for everything to be displayed on a page. Under the requirements of the business scenario, we need to display different components according to different URLs or different hashes. We can call this route. How do we do routing when we are not using React-router?

I'll give you an example here, without using React-router, to implement a simple route.

  // 
import React,{Component} from 'react'
export default class App extends Component {
  constructor(){
    super()
  // We are rendering different components internally. We use hash routing here. Given the rendering mechanism of React, we need to bind the value into the state.    ={
      route:(1)
    }
  }
  componentDidMount() {
    // Here we listen to the hash changes through listening, and update the state to promote view update    ('hashchange', () => {
      ((1))
     ({
      route: (1)
     })
    })
   }
  render() {
    //Here we define a RouterView All the changed components will be thrown into this RouterView.    let RouterView = App
    switch () {
      case '/children1':
      RouterView = Children
        break;
      case '/children2':
      RouterView = ChildrenTwo
        break;
      default:
      RouterView = Home
        break;
    }
    return (
      <div>  
        <h1>App</h1>
        <ul>
          <li><a href="#/children1" rel="external nofollow" >children1</a></li> 
          {/* Click to change the hash value. Here we trigger our listening and then modify the state to trigger the reinfection of the component */}
          <li><a href="#/children2" rel="external nofollow" >children2</a></li>
        </ul>
        <RouterView/>
      </div>
    )
  }
}

// Define subcomponents for displaying effects
class Children extends Component{
  constructor(){
    super()
    ={
      
    }
  }
  render(){
    return(
      <div>
        <h1>I'm a child component1</h1>
        
      </div>
    )
  }
}

// Define subcomponent two for displaying effects
class ChildrenTwo extends Component{
  constructor(){
    super()
    ={
    
    }
  }
  render(){
    return(
      <div>
        <h1>I'm a child component2</h1>
      </div>
    )
  }
}
// Define Home component for display effectclass Home extends Component{
  constructor(){
    super()
  }
  render(){
    return(
      <h1>I amHome</h1>
    )
  }
}

In this way, we realize our first simple route by listening for hash changes. Do you have such a little understanding of the principle of routing? Next we imagine a scenario where such a route appears /children1/user/about/1. Do you think that using switch case has been bounced? Next we will use React-router. This thing doesn’t require us to write a large number of switch cases ourselves, and the performance, cleanliness and so on are much better than what we write ourselves!

React-router First experience

First, we execute it in the React project file directory

npm install react-router-dom --save
npm install react-router --save

To experience something new, of course, we have to use our own actions. We have improved the components we have written above

// 
import React,{Component} from 'react'
// First we need to import some components...import { HashRouter as Router, Route, Link } from "react-router-dom";
// Here are two modes: BrowserRouter and HashRouter. I recommend HashRouter to learn. BrowserRouter requires backend cooperation. A separate front-end setting will appear 404 when refreshing.// Then we sorted out the App components, probably like thisexport default class App extends Component {
  constructor(){
    super()
    ={
     
    }
  }
  render() {
    return (
      <Router>
        <div>
        <h1>App</h1>
        <ul>
          <li> <Link to="/">Home</Link></li> 
          <li><Link to="/children1/">children1</Link></li>
          <li><Link to="/children2/">children2</Link></li>
        </ul>
        <Route exact path="/" component={Home} />
        <Route path="/children1" component={Children} />
        <Route path="/children2" component={ChildrenTwo} />
        </div>
      </Router>
    )
  }
}

// Define subcomponents for displaying effectsclass Children extends Component{
  constructor(){
    super()
    ={
      
    }
  }
  render(){
    return(
      <div>
        <h1>I'm a child component1</h1>
      </div>
    )
  }
}
// Define subcomponent two for displaying effectsclass ChildrenTwo extends Component{
  constructor(){
    super()
    ={
    
    }
  }
  render(){
    return(
      <div>
        <h1>I'm a child component2</h1>
      </div>
    )
  }
}
// Define Home component for display effectclass Home extends Component{
  constructor(){
    super()
  }
  render(){
    return(
      <h1>I amHome</h1>
    )
  }
}

Here we have completed the initial experience, how about it? I gave you the first time I feel OK~

Basic Components

Routers

In React-router 4.0, Routers have two ways of presenting <BrowserRouter>and <HashRouter>Both tags will create a special history object for you, and the BrowserRouter's presentation mode needs to be paired with a server that can respond to requests. HashRouter is a static file server. When we develop locally, we recommend using HashRouter. It should be noted here that only one tag is allowed under the BrowserRouter and HashRouter tags. The specific writing method is as follows

&lt;BrowserRouter&gt;
  &lt;div&gt;
    {/*The rest of the content is written here*/}
  &lt;/div&gt;
&lt;/BrowserRouter&gt;

&lt;HashRouter&gt;
  &lt;div&gt;
    {/*The rest of the content is written here*/}
  &lt;/div&gt;
&lt;/HashRouter&gt;

Route

Note that the outermost layer is Router. Here is Route. This is our route matching component. It has two Routes and Switch.

The Route component has multiple properties, which will be used in our later routing parameters. Here we need to briefly understand several attributes path component exact strict

path is the address we match. When the address matches, we will render the component content in the component.

If the writing mode after path contains /: this content, then it will become a placeholder. We can use the placeholder to get the parameters of the corresponding path. Use the name of the + placeholder to get it.

Exact attribute to specify whether we strictly match

strict is a strict matching pattern. The path we stipulate is written using /one/. If there is no exact match, then it will not be displayed.

&lt;Route exact path="/one" component={App} /&gt;
// We added exact here, then the App will be rendered when the path is completely equal to /one /one/one/two. The following three situations will not be rendered.
// On the contrary, if we do not add exact, the /one /one/two App will be rendered
&lt;Route strict path="/one/" component={App} /&gt;
// After we add strict, /one will not render the App. If there is no strict, /one can render the App.

At the same time, React-router provides us with a Switch tag. In this tag, we will only render a Route and make the first Route that meets the criteria. What does this mean? Let's look at the code

<Route path="/about" component={About} />
<Route path="/:User" component={User} />
<Route path="/" component={Home} />
<Route component={NoMatch} />

Under such a route, we will find that all routes can be matched and rendered, which is definitely not the result we want. So we nest a Switch for it

<Switch>
  <Route path="/about" component={About} />
  <Route path="/:User" component={User} />
  <Route path="/" component={Home} />
  <Route component={NoMatch} />
</Switch>

At this time, we will only match the first /about, just render About, and decide whether to use the Switch according to actual needs.

Link and NavLink

Link's main api is to, to can accept string or object to control url. Let's see how to write in our code

  &lt;Link to='/one/' /&gt; 
  // This is how to use it with Router. Of course we can use an object
  &lt;Link to={{
    pathname:'/one',
    search:'?name=qm',
    hash:'#two',
    state:{
      myName:'qimiao'
    }
  }} /&gt;
  // In this way, we can click link to not only one, but also pass some parameters

NavLink It can set class names, styles, callback functions, etc. for the currently selected route. Use as follows

  &lt;NavLink exact activeClassName='navLink' to='/one/' /&gt; 
  // This is how to use it with Router. Of course we can use an object
  &lt;NavLink exact activeClassName='navLink' to={{
    pathname:'/one',
    search:'?name=qm',
    hash:'#two',
    state:{
      myName:'qimiao'
    }
  }} /&gt;
  // The exact here is also strictly matching mode. The same as Route  // This way we can set the style for the currently selected route

Writing of subroutines

In versions before react-router4, subrouter can be implemented by routing nesting, but this method will not work in React-router4.

Let's first write a previous way, of course it's also an error example

export default class App extends Component {
  constructor(){
    super()
    ={
     
    }
  }
  render() {
    return (
      &lt;Router&gt;
        &lt;div&gt;
        &lt;h1&gt;App&lt;/h1&gt;
        &lt;ul&gt;
          &lt;li&gt; &lt;Link to="/home"&gt;Home&lt;/Link&gt;&lt;/li&gt; 
          &lt;li&gt;&lt;Link to="/children1/"&gt;children1&lt;/Link&gt;&lt;/li&gt;
          &lt;li&gt;&lt;Link to="/children2/"&gt;children2&lt;/Link&gt;&lt;/li&gt;
        &lt;/ul&gt;
        &lt;Route path="/home" component={Home} &gt;
          &lt;Route path="children1" component={Children} /&gt;
          &lt;Route path="children2" component={ChildrenTwo} /&gt;
          {/*In versions after 4.0, this will be reported incorrectly. So how should we write it*/}
        &lt;/Route&gt;
      
        &lt;/div&gt;
      &lt;/Router&gt;
    )
  }
}

In the version, our subroutine must be inside the subcomponent

export default class App extends Component {
  constructor(){
    super()
    ={
     
    }
  }
  render() {
    return (
      &lt;Router&gt;
        &lt;div&gt;
        &lt;h1&gt;App&lt;/h1&gt;
        &lt;ul&gt;
          &lt;li&gt; &lt;Link to="/home"&gt;Home&lt;/Link&gt;&lt;/li&gt; 
          {/* Similarly, these two links allow them to be transferred to Home Our home component becomes the following */}
        &lt;/ul&gt;
        &lt;Route path="/home" component={Home} &gt;
         {/*&lt;Route path="children1" component={Children} /&gt;*/} 
         {/*&lt;Route path="children2" component={ChildrenTwo} /&gt;*/} 
          {/*Comment out here first and then we come to the Home component*/}
        &lt;/Route&gt;
      
        &lt;/div&gt;
      &lt;/Router&gt;
    )
  }
}

// Use {+ subroutine path} inside home to get the current path and add the location we want to route to match and path jump matching in this way Children and ChildrenTwo are the subroutines of homeclass Home extends Component{
  constructor(){
    super()
  }
  
  render(){
    return(
      &lt;div&gt;
      &lt;h1&gt;I amHome&lt;/h1&gt;
      &lt;li&gt;&lt;Link to={`${}/children1`}&gt;children1&lt;/Link&gt;&lt;/li&gt;
      &lt;li&gt;&lt;Link to={`${}/children2`}&gt;children2&lt;/Link&gt;&lt;/li&gt;
      &lt;Route path={`${}/children1`} component={Children} /&gt;
      &lt;Route path={`${}/children2`} component={ChildrenTwo} /&gt;   
      &lt;/div&gt;
    )
  }
}

Routing jump

Declarative jump has been mentioned above. The two labels Link and NavLink can satisfy us. Let’s mainly talk about js jump.

When 4.0 was just released ('path') this method no longer works, but thankfully, the version 4.3.1 I am using now can use this method to perform js routing jumps.

Let's use the home component to give an example

class Home extends Component{
  constructor(){
    super()
  }
  toPath=(home)=&gt;{
    (123)
    ({ //We put all the things we want to pass the arguments in the push object      pathname:home,  //Which route should we reach      search:"?a=1",  //The mode of clear text transmission      query:{'type':'type'}, //Query object parameter transmission      state:{     //State object parameter        b:456
      }
    })
  // ('/123')
  }
  render(){
    return(
      &lt;div&gt;
      &lt;h1 onClick={()=&gt;{(`${}/children1/123`)}}&gt;I amHome&lt;/h1&gt;
      &lt;li&gt;&lt;Link to={`${}/children1`}&gt;children1&lt;/Link&gt;&lt;/li&gt;
      &lt;li&gt;&lt;Link to={`${}/children2`}&gt;children2&lt;/Link&gt;&lt;/li&gt;
      &lt;Route path={`${}/children1/:id`} component={Children} /&gt;
      &lt;Route path={`${}/children2`} component={ChildrenTwo} /&gt;   
      &lt;/div&gt;
    )
  }
}

/* Corresponding We have corresponding methods in the Children component to obtain parameters.  */

class Children extends Component{
  constructor(){
    super()
    ={
      
    }
  }
  render(){
    () //This is a parameter passed through the id on the path    () //This is passed through the query in the push parameter object. There is a difference between it and the query of vue. It is not in the address bar. Refresh is lost.    () //This is passed through the state in the push parameter object. It is not in the address bar. Refresh is missing.    () //Exposed to the address bar, you need to process and obtain data by yourself

    return(
      &lt;div&gt;
        &lt;h1&gt;I am子组件1 &lt;/h1&gt;
      &lt;/div&gt;
    )
  }
}

Summarize

In this issue, we mainly talked about the basic usage and transmission methods. There are many pitfalls, but if you use them proficiently, you will feel very happy. Don’t be stingy with your time to learn more.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.