react【六】 React-Router

文章目录

  • 1、Router
    • [1.1 路由](#1.1 路由)
    • [1.2 认识React-Router](#1.2 认识React-Router)
    • [1.3 Link和NavLink](#1.3 Link和NavLink)
    • [1.4 Navigate](#1.4 Navigate)
    • [1.5 Not Found页面配置](#1.5 Not Found页面配置)
    • [1.6 路由的嵌套](#1.6 路由的嵌套)
    • [1.7 手动路由的跳转](#1.7 手动路由的跳转)
      • [1.7.1 在函数式组件中使用hook](#1.7.1 在函数式组件中使用hook)
      • [1.7.2 在类组件中封装高阶组件](#1.7.2 在类组件中封装高阶组件)
    • [1.8 动态路由传递参数](#1.8 动态路由传递参数)
    • [1.9 路由的配置文件以及懒加载](#1.9 路由的配置文件以及懒加载)

1、Router

1.1 路由





1.2 认识React-Router

npm install react-router-dom





js 复制代码
import React, { PureComponent } from "react";
import { Navigate } from "react-router-dom";

export class Login extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      isLogin: false,
    };
  }

  login() {
    this.setState({ isLogin: true });
  }

  render() {
    const { isLogin } = this.state;

    return (
      <div>
        <h1>Login Page</h1>
        {/* 如果没有登录的话显示登录按钮
            已经登录则跳转到/home页面 */}
        {!isLogin ? (
          <button onClick={(e) => this.login()}>登录</button>
        ) : (
          <Navigate to="/home" />
        )}
      </div>
    );
  }
}

export default Login;

1.5 Not Found页面配置

js 复制代码
      <Routes>
         <Route path="*" element={<NotFound />} />
      </Routes>

1.6 路由的嵌套

1.7 手动路由的跳转

1.7.1 在函数式组件中使用hook

1.7.2 在类组件中封装高阶组件


1.8 动态路由传递参数

  • hoc
js 复制代码
import {
  useLocation,
  useNavigate,
  useParams,
  useSearchParams,
} from "react-router-dom";

const withRouter = (WrapperComponent) => {
  return (props) => {
    // 1.导航
    const navigate = useNavigate();

    // 2.动态路由的参数 :/detail/:id
    const params = useParams();

    // 3.查询字符串的参数: /user?name=why&age=18
    const location = useLocation();

    const [searchParams] = useSearchParams();
    const query = Object.fromEntries(searchParams);

    // Object.fromEntries([
    //   ["a", "b"],
    //   ["c", "d"],
    // ]);
    //Object{a:"b", c:"d"}

    const router = { navigate, params, location, query };

    return <WrapperComponent {...props} router={router} />;
  };
};

export default withRouter;
js 复制代码
import React, { PureComponent } from 'react'
import { withRouter } from '../hoc'

export class Detail extends PureComponent {
  render() {
    const { router } = this.props
    const { params } = router

    return (
      <div>
        <h1>Detail Page</h1>
        <h2>id: {params.id}</h2>
      </div>
    )
  }
}

export default withRouter(Detail)
js 复制代码
import React, { PureComponent } from 'react'
import { withRouter } from '../hoc'

export class User extends PureComponent {
  render() {
    const { router } = this.props
    const { query } = router

    return (
      <div>
        <h1>User: {query.name}-{query.age}</h1>
      </div>
    )
  }
}

export default withRouter(User)

1.9 路由的配置文件以及懒加载

js 复制代码
import Home from "../pages/Home";
import HomeRecommend from "../pages/HomeRecommend";
import HomeRanking from "../pages/HomeRanking";
import HomeSongMenu from "../pages/HomeSongMenu";
// import About from "../pages/About"
// import Login from "../pages/Login"
import Category from "../pages/Category";
import Order from "../pages/Order";
import NotFound from "../pages/NotFound";
import Detail from "../pages/Detail";
import User from "../pages/User";
import { Navigate } from "react-router-dom";
import React from "react";

// import 返回的是一个Promise
const About = React.lazy(() => import("../pages/About"));
const Login = React.lazy(() => import("../pages/Login"));

const routes = [
  {
    path: "/",
    // 重定向
    element: <Navigate to="/home" />,
  },
  {
    path: "/home",
    element: <Home />,
    children: [
      // 子路由
      {
        path: "/home",
        element: <Navigate to="/home/recommend" />,
      },
      {
        path: "/home/recommend",
        element: <HomeRecommend />,
      },
      {
        path: "/home/ranking",
        element: <HomeRanking />,
      },
      {
        path: "/home/songmenu",
        element: <HomeSongMenu />,
      },
    ],
  },
  {
    path: "/about",
    element: <About />,
  },
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/category",
    element: <Category />,
  },
  {
    path: "/order",
    element: <Order />,
  },
  {
    path: "/detail/:id",
    element: <Detail />,
  },
  {
    path: "/user",
    element: <User />,
  },
  {
    path: "*",
    element: <NotFound />,
  },
];

export default routes;
js 复制代码
// import { StrictMode } from "react"
import ReactDOM from "react-dom/client";
import App from "./App";
import { HashRouter } from "react-router-dom";
import { Suspense } from "react";

const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(
  // <StrictMode>
  <HashRouter>
    // 需要加上Suspense 如果数据js 和 css文件还没请求回来就显示这里的内容
    <Suspense fallback={<h3>Loading...</h3>}>
      <App />
    </Suspense>
  </HashRouter>
  // </StrictMode>
);
相关推荐
柯南二号7 分钟前
HarmonyOS ArkTS 下拉列表组件
前端·javascript·数据库·harmonyos·arkts
wyy72939 分钟前
v-html 富文本中图片使用element-ui image-viewer组件实现预览,并且阻止滚动条
前端·ui·html
前端郭德纲21 分钟前
ES6的Iterator 和 for...of 循环
前端·ecmascript·es6
究极无敌暴龙战神X24 分钟前
前端学习之ES6+
开发语言·javascript·ecmascript
王解27 分钟前
【模块化大作战】Webpack如何搞定CommonJS与ES6混战(3)
前端·webpack·es6
欲游山河十万里28 分钟前
(02)ES6教程——Map、Set、Reflect、Proxy、字符串、数值、对象、数组、函数
前端·ecmascript·es6
明辉光焱28 分钟前
【ES6】ES6中,如何实现桥接模式?
前端·javascript·es6·桥接模式
PyAIGCMaster1 小时前
python环境中,敏感数据的存储与读取问题解决方案
服务器·前端·python
baozhengw1 小时前
UniAPP快速入门教程(一)
前端·uni-app
nameofworld1 小时前
前端面试笔试(二)
前端·javascript·面试·学习方法·数组去重