App.js

/** 01 路由参数占位符 动态路由通过 :style 的形式实现;由于 /goods/list 的匹配度大于 /goods/ ,所以输入精确地址,会精确匹配,而不是匹配到动态路由;

* 02 触发操作的时候传递具体的参数

* 03 在具体的组件当中使用传递的参数

*/ importReact, { Component } from‘react’ import {Link,Route,Routes} from‘react-router-dom’ importHomefrom‘./components/home’ importListfrom‘./components/list’ importNotFoundfrom‘./components/notFound’ importDetailfrom‘./components/detail’ classAppextendsComponent { render() { return ( <div> <div> <Linkto=“/home”>shouye</Link>—— <Linkto=“/list”>liebiaoye</Link> </div> <div> <Routes> <Routepath=“/“element={<Home/>}exact/> <Routepath=“/home”element={<Home/>}/> <Routepath=“/list”element={<List/>}/> <Routepath=“/detail/:idelement={<Detail/>}/> <Routeelement={<NotFound/>}/> </Routes> </div> </div> ) } } exportdefaultApp

List.js

importReact, { Component } from‘react’ import { Link } from‘react-router-dom’ classListextendsComponent { render() { return ( <div> //传递参数 <p><Linkto=“/detail/1”>测试文章1</Link></p> <p><Linkto=“/detail/2”>测试文章2</Link></p> </div> ) } } exportdefaultList

detail.js

importReact, { Component } from‘react’ classDetailextendsComponent { render(props) { console.log(this.props.match.params.id) return ( <div>{this.props.match.params.id}</div> ) } } exportdefaultDetail useParams 获取动态路由的值; useSearchParams 获取查询字符串的值。

// GoodsDetail.tsx

import React,{ useEffect } from “react”;

import { useParams, useSearchParams } from “react-router-dom”;

export default function GoodsDetail() {

// 获取动态路由的值

const params = useParams();

// 获取查询字符串的值

const [searchParams, setSearchParams] = useSearchParams(); useEffect(() => { // 一个对象,key 为动态字符串的 key console.log(params); // {id: ‘123’}
  1. // 一个对象,但是不可直接点出属性
  2. console.log(typeof searchParams); // object
  3. // 输入 [http://localhost:3304/goods/123?name=nihao](http://localhost:3304/goods/123?name=nihao)
  4. console.log(<font style="color:#F5222D;">searchParams.get("name")</font>); // <font style="color:#F5222D;">nihao</font>

}, []);

const handleAddParams = () => {

  1. // 修改 查询字符串 的数据
  2. <font style="color:#F5222D;">setSearchParams</font>({
  3. name:"xxx"
  4. });

};

return (

  1. <div>
  2. <h2 onClick={handleAddParams}>GoodsDetail Page</h2>
  3. </div>

);

}