React routing usage - detailed introduction

image.png

Initial use of routing

image.png

abstract routing module

image.png

src\page\Article\index.js

const Article = () => {
    
    
  return (
    <div>
      <p>文章页</p>
    </div>
  );
};

export default Article;

src\router\index.js

// 导入页面
import Article from "../page/Article";
import Login from "../page/LogIn";

import {
    
     createBrowserRouter } from "react-router-dom";

// 创建 router 实例对象并配置路由对应关系
const router = createBrowserRouter([
  {
    
     path: "/login", element: <Login /> },
  {
    
     path: "/article", element: <Article /> },
]);

export default router;

src\index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import reportWebVitals from "./reportWebVitals";

/*
前端路由
一个路径 path 对应一个组件 component 当我们在浏览器中访问一个 path 的时候,path 对应的组件会在页面中进行渲染
*/
import {
    
     RouterProvider } from "react-router-dom";
// 导入路由
import router from "./router";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <RouterProvider router={
    
    router}></RouterProvider>
  </React.StrictMode>
);

reportWebVitals();

Jump parameter

Two ways to jump

Method 1 : Declarative navigation jump, the principle is to convert to a tag

      <Link to="/login">跳转到登录</Link>

Method 2 : Imperative navigation, programmatic navigation refers to getting the navigation method through the useNavigate" hook, and then calling the method to perform routing jumps in the form of commands. For example, if you want to jump after the login request is completed, you can choose this method. more flexible

Grammar description: Jump by calling the navigate method to pass in the address path

      <button onClick={
    
    () => navigate("/login")}>跳转登录</button>

Two ways of passing parameters

method one

pass parameters

image.png

take over

image.png

way two

configuration

image.png

pass parameters

image.png

take over

image.png

Configure nested routes

children are used to configure the nesting of routes, and Outlet is the exit of nested routes

image.png

use routing

image.png

Guess you like

Origin blog.csdn.net/wbskb/article/details/132004089