[React Family Bucket] The use of React routing - react-router-dom (routing switching, getting routing parameters, routing nesting, 404) contains source code

1. Guidance

The purpose of using React routing is to implement SPA (single page application), which is characterized by a single page (only one html file) and multiple components.

2. Use react-router-dom

注意:这里要区分路由库的版本,我这里的版本是v6

1、安装react-router-dom:npm install react-router-dom

2. Introduce the route in the entry file src/index.js and wrap it with the route type

/*src/index.js*/
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import {
    
     BrowserRouter as Router } from "react-router-dom";

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById('root')
);

3. Introduce routing in the component that needs to use routing (RouterDemo)

The Link tag is similar to the a tag, the to attribute indicates which component to jump to, and the name is customized.
The role of the Route tag is to register components, the path attribute indicates the same path as defined by Link, and the element attribute indicates the component to be displayed.
注意:v6版本需要在Route标签外包上Routes标签。

/*RouterDemo/index.jsx*/
import React, {
    
     Component } from 'react';
import {
    
     Link, Route, Routes } from 'react-router-dom';
import Home from './Home';
import About from './About';

export default class RouterDemo extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <div className="row">
                    <div className="col-xs-offset-2 col-xs-8">
                        <div className="page-header"><h2>React Router Demo</h2></div>
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-2 col-xs-offset-2">
                        <div className="list-group">
                            {
    
    /* react中靠路由链接切换组件 */}
                            <Link className="list-group-item" to="/about">About</Link>
                            <Link className="list-group-item" to="/home">Home</Link>
                        </div>
                    </div>
                    <div className="col-xs-6">
                        <div className="panel">
                            <div className="panel-body">
                                {
    
    /* 注册路由 */}
                                <Routes>
                                    <Route path="/:name" element={
    
    <About />} />
                                    <Route path="/home" element={
    
    <Home />} />
                                </Routes>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
/*App.js*/
import React, {
    
     Component } from 'react';
import RouterDemo from './components/RouterDemo';

export default class APP extends Component {
    
    
  render() {
    
    
    return (
      <div id="root">
          <RouterDemo />
      </div>
    );
  }
}

/*About/index.jsx*/
import React, {
    
     Component } from 'react';

export default class About extends Component {
    
    
    render() {
    
    
        return <h3>我是About的内容</h3>;
    }
}
/*Home/indx.jsx*/
import React, {
    
     Component } from 'react';

export default class Home extends Component {
    
    
    render() {
    
    
        return <h3>我是Home的内容</h3>;
    }
}

insert image description here

3. Get the parameters in the route

1、useLocation

useLocation is to get the information of the current route.
insert image description here

2、useParams

useParams is to obtain the content of the path attribute set by **:key** in the Route tag in the current route.

/*RouterDemo/index.jsx*/
<Route path="/:name" element={
    
    <About />} />

insert image description here

Instructions:

/*About/index.jsx*/
import React from 'react';
import {
    
     useLocation, useParams } from 'react-router-dom';

export default function About() {
    
    
    const location = useLocation();
    const param = useParams();
    console.log('useLocation', location)
    console.log('useParams', param)
    return (<h3>我是About的内容-{
    
    param.name}-{
    
    location.search ? location.search : ''}</h3>);
}

insert image description here

Fourth, use useavigate for routing switching

假设我们在About路由中添加一个按钮,功能为跳转到Home路由

1. First, we need to introduce useNavigate from react-router-dom;

2. Call: const to = useNavigate();
insert image description here

3. Write the click event on the button

/*About/index.jsx*/
<button onClick={
    
    () => {
    
     to('/Home') }}>Home</button>

insert image description here

Five, nested routing

1. First write two nested routes, nested in About

insert image description here

/*About/index.jsx*/
import React from 'react';
import {
    
     useLocation, useParams, useNavigate, Link, Routes, Route } from 'react-router-dom';
import Router2 from './router2';
import Router1 from './router1';

export default function About() {
    
    
    const location = useLocation();
    const param = useParams();
    const to = useNavigate();
    console.log('useLocation', location)
    console.log('useParams', param)
    console.log('useNavigate', to)

    return (
        <div>
            <h3>我是About的内容-{
    
    param.name}-{
    
    location.search ? location.search : ''}</h3>
            <button onClick={
    
    () => {
    
    
                to('/Home')
            }}>Home</button>
            <hr />
            <Link to='/About'>嵌套路由1</Link>
            <Link to='/About/2'>嵌套路由2</Link>
            <Routes>
                <Route path="" element={
    
    <Router1 />}></Route>
                <Route path="2" element={
    
    <Router2 />}></Route>
            </Routes>
        </div>);
}
//注意Link和Route中的to和path规范

insert image description here
完成!!!

6. 404 page

当地址栏找不到相应页面的时候就会跳出404页面

1. First create an exception folder in the RouterDemo folder, and create a new 404.jsx in it
insert image description here

2. In the About component, introduce a 404 page

/*About/index.jsx*/
import React from 'react';
import {
    
     useLocation, useParams, useNavigate, Link, Routes, Route } from 'react-router-dom';
import Router2 from './router2';
import Router1 from './router1';
import PageNotFound from '../exception/404';

export default function About() {
    
    
    const location = useLocation();
    const param = useParams();
    const to = useNavigate();
    console.log('useLocation', location)
    console.log('useParams', param)
    console.log('useNavigate', to)

    return (
        <div>
            <h3>我是About的内容-{
    
    param.name}-{
    
    location.search ? location.search : ''}</h3>
            <button onClick={
    
    () => {
    
    
                to('/Home')
            }}>Home</button>
            <hr />
            <Link to='/About'>嵌套路由1</Link>
            <Link to='/About/2'>嵌套路由2</Link>
            <Routes>
                <Route path="" element={
    
    <Router1 />}></Route>
                <Route path="2" element={
    
    <Router2 />}></Route>
                <Route path="*" element={
    
    <PageNotFound />} />
            </Routes>
        </div>);
}
//注意:404页面的Route中,path='*'表示如果二级路由除了""或者"2"的名字外,就会显示404

insert image description here
完成!!!

Source address: https://gitee.com/daiwanghao/react-family-bucket.git

The above is the use of React routing, please pay attention to the " React Family Bucket " column.
I will share the common problems in my usual projects and the knowledge of the written test and interview with you on CSDN, and make progress together. Come on.

Guess you like

Origin blog.csdn.net/weixin_46318413/article/details/122721147