React - Introduction to Basic Use of Router

Introduction to the basic use of Router

Meet React-Router

At present, the three popular front-end frameworks all have their own routing implementations :

Angular-ngRouter

React的ReactRouter

Vue vue-router

React Router has been updated quickly in the past two years, and has undergone major changes in the latest React Router6.x version .

Currently React Router6.x is very stable, we can use it with confidence;

Let me explain, there is not much difference between Router4.x and Router5.x, but there are some differences between Router6.x, so the Router series of articles mainly explain Router6.x, and when there are differences from version 4 or 5, it will be separate emphasis

Install React Router :

When installing, we choose to install react-router-dom, npm install react-router-dom;

Because react-router will contain some react-native content, web development does not need;


Router component API

The main API of react-router is to provide us with some components :

BrowserRouter or HashRouter

Router contains the listener for path changes, and will pass the corresponding paths to subcomponents;

BrowserRouter uses history mode;

import React from "react"
import ReactDOM from "react-dom/client"
import {
    
     BrowserRouter } from "react-router-dom"
import App from "./App"

const root = ReactDOM.createRoot(document.querySelector("#root"))

root.render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>
)

HashRouter uses hash mode

import React from "react"
import ReactDOM from "react-dom/client"
import {
    
     HashRouter } from "react-router-dom"
import App from "./App"

const root = ReactDOM.createRoot(document.querySelector("#root"))

root.render(
  <HashRouter>
    <App/>
  </HashRouter>
)

Router mapping configuration

Routes: Wrap all Routes and match a route among them

Router6.x uses the Routes component

Router5.x uses the Switch component

Route: Route is used for path matching ;

Router6.x does not allow the Router component to exist alone

path attribute : used to set the matched path;

element attribute : set the rendered component after matching the path;

  • Router5.x uses the component attribute

exact : exact match, the corresponding component will be rendered only when the exact path is matched exactly;

  • Router6.x no longer supports this attribute
<div className='app'>
  <div className='header'>header</div>
  
  <div className='counter'>
    <Routes>
      <Route path='/' element={<Home/>}/>
      <Route path='/about' element={<About/>}/>
      <Route path='/profile' element={<Profile/>}/>
    </Routes>
  </div>
  
  <div className='footer'>footer</div>
</div>

Router configuration and jump

Link组件:

Usually the jump of the path is to use the Link component, which will eventually be rendered as an element;

NavLink adds some style attributes on the basis of Link (will be explained later);

to attribute : the most important attribute in Link, used to set the path to jump to

For example, to implement the above code, we realize the effect of clicking the button to switch pages in the header

<div className='app'>
  <div className='header'>
    <Link to="/">首页</Link>
    <Link to="/about">关于</Link>
    <Link to="/profile">我的</Link>
  </div>

  <div className='counter'>
    <Routes>
      <Route path='/' element={
    
    <Home/>}/>
      <Route path='/about' element={
    
    <About/>}/>
      <Route path='/profile' element={
    
    <Profile/>}/>
    </Routes>
  </div>

  <div className='footer'>footer</div>
</div>

NavLink组件

Requirement: When the path is selected, the text of the corresponding a element turns red

At this time, we will use the NavLink component to replace the Link component. When the NavLink component is selected, a class is added (you can understand this component, it is more convenient to control it yourself ) :

In fact, when the default matching is successful, NavLink will dynamically add a class: active, which will be added when selected;

So we can also directly write styles

Of course, if you are worried that this class is used in other places, there will be a cascade of styles, you can also customize the class and add styles dynamically

style attribute : pass in a function, and the parameter of the function receives an object, which contains the isActive attribute

<NavLink to="/" style={
     
     ({
      
       isActive }) => ({
     
     color: isActive ? "red" : ""})}>首页</NavLink>
<NavLink to="/about" style={
     
     ({
      
       isActive }) => ({
     
     color: isActive ? "red" : ""})}>关于</NavLink>
<NavLink to="/profile" style={
     
     ({
      
       isActive }) => ({
     
     color: isActive ? "red" : ""})}>我的</NavLink>

className : pass in a function whose parameter accepts an object that contains the isActive property

<NavLink to="/" className={
     
     ({
      
       isActive }) => isActive ? "my-class" : ""}>首页</NavLink>
<NavLink to="/about" className={
     
     ({
      
       isActive }) => isActive ? "my-class" : ""}>关于</NavLink>
<NavLink to="/profile" className={
     
     ({
      
       isActive }) => isActive ? "my-class" : ""}>我的</NavLink>

The Navigate component uses

Navigate is used for routing 重定向. When this component appears, it will jump to the corresponding to path :

A case where we use this here :

The user jumps to the Profile interface;

But there is an isLogin in the Profile interface to record whether the user is logged in:

  • true: means logged in, jump to the home page;
  • false: means not logged in, explicit login button;
export class Profile extends PureComponent {
    
    
  constructor(props) {
    
    
    super(props)

    this.state = {
    
    
      isLogin: false
    }
  }

  login() {
    
    
    this.setState({
    
    
      isLogin: true
    }) 
  }

  render() {
    
    
    const {
    
     isLogin } = this.state
    console.log(isLogin)

    return (
      <div>
        <h2>Profile</h2>
        {
    
    /* 为true时重定向到首页 */}
        {
    
    isLogin ? <Navigate to="/home" /> : <button onClick={
    
    () => this.login()}>登录</button>}
      </div>
    )
  }
}

We can also jump directly to the "/home" page when "/" is matched

<Routes>
  {
    
    /* 当默认路径 / 时, 重定向到home页面 */}
  <Route path='/' element={
    
    <Navigate to="/home"/>}></Route>
  <Route path='/home' element={
    
    <Home/>}/>
  <Route path='/about' element={
    
    <About/>}/>
  <Route path='/profile' element={
    
    <Profile/>}/>
</Routes>

Not Found page configuration

If the user randomly enters an address that cannot be matched, nothing will be displayed where the route matches.

Many times, we want users to see a Not Found page in this case .

The process is very simple :

Develop a Not Found page;

Configure the corresponding Route, and set the path to *;

<Routes>
  {
    
    /* 当默认路径 / 时, 重定向到home页面 */}
  <Route path='/' element={
    
    <Navigate to="/home"/>}></Route>
  <Route path='/home' element={
    
    <Home/>}/>
  <Route path='/about' element={
    
    <About/>}/>
  <Route path='/profile' element={
    
    <Profile/>}/>
  {
    
    /* 当上面路径都没有匹配到时, 显式Notfound组件 */}
  <Route path='*' element={
    
    <Notfound/>}/>
</Routes>

Guess you like

Origin blog.csdn.net/m0_71485750/article/details/126789192