detail.js

//V6通过 useNavigate 方法跳转;

// Goods.tsx

import React from “react”;

import { useNavigate } from “react-router-dom”;

export default function Goods() {

const navigate = useNavigate();

const handleClickToHome = () => {

  1. <font style="color:#F5222D;">navigate("/");</font>
// history 的 replace 模式 // navigate(“/“, { replace: true });

};

return (

  1. <div>
  2. <h2>Goods Page</h2>
  3. <button onClick={handleClickToHome}>to Home</button>
  4. </div>

);

}

importReact, { Component } from‘react’ import { createHashHistory } from‘history’ classDetailextendsComponent { render(props) { console.log(this.props.match.params.id) return ( <div> <p>{this.props.match.params.id}</p> <button onClick={() => { createHashHistory().push(‘/home’) }}>点击跳转至首页</button> </div> ) } } exportdefaultDetail

home.js

//v6 移除了 Redirect 组件,改用 Navigate 组件。

// Router.tsx

import React from “react”;

import { BrowserRouter, Route, Routes, Navigate } from “react-router-dom”;

import Home from “../home/Home”;

import Goods from “../goods/Goods”;

import Customer from “../customer/Customer”;

import NotFound from “../not-found/NotFound”;

export default function Router() {

{/ 所有的路由配置均在 BrowserRouter 内部 / }

return (

  1. <BrowserRouter>
  2. {/* 使用 Routes 替换曾经的 Switch */}
  3. <Routes>
  4. <Route path='/' element={<Home />} />
  5. <Route path='goods' element={<Goods />} />
  6. <Route path='customer' element={<Customer />} />
  7. {/* 重定向到首页 */}
  8. <Route path="*" element={<font style="color:#F5222D;"><Navigate to="/"/</font>>} />
  9. {/* 或者跳转到 NotFound */}
  10. {/* <Route path="*" element={<NotFound />} /> */}
  11. </Routes>
  12. </BrowserRouter>

);

}

importReact, { Component } from‘react’ importqsfrom‘qs’ import { Redirect } from‘react-router-dom’ classHomeextendsComponent { render(props) { // console.log(this.props.location.search) // console.log(qs.parse(this.props.location.search, { ignoreQueryPrefix: true })) const isLogin = false if (!isLogin) { return <Redirect to=“/list”/> } return ( <div>Home 首页内容 {qs.parse(this.props.location.search, { ignoreQueryPrefix:true }).title}</div> ) } } exportdefaultHome