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 = () => {
// history 的 replace 模式 // navigate(“/“, { replace: true });
<font style="color:#F5222D;">navigate("/");</font>
};
return (
<div>
<h2>Goods Page</h2>
<button onClick={handleClickToHome}>to Home</button>
</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> ) } } exportdefaultDetailhome.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 (
<BrowserRouter>
{/* 使用 Routes 替换曾经的 Switch */}
<Routes>
<Route path='/' element={<Home />} />
<Route path='goods' element={<Goods />} />
<Route path='customer' element={<Customer />} />
{/* 重定向到首页 */}
<Route path="*" element={<font style="color:#F5222D;"><Navigate to="/"/</font>>} />
{/* 或者跳转到 NotFound */}
{/* <Route path="*" element={<NotFound />} /> */}
</Routes>
</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