React 中除了react-router还有哪些路由方案

在用React开发时,常用的路由是react-router ,但除此之外,还有两个路由方案,因为他们具备 react-router 没有的特性。

1. @tanstack/router

1.1. 主要特性

  • 100% 推断的 TypeScript 支持

  • 类型安全的导航

  • 嵌套路由和布局路由

  • 内置的路由加载器,带有 SWR 缓存

  • 为客户端数据缓存设计(如 TanStack Query、SWR 等)

  • 自动路由预取

  • 异步路由元素和错误边界

  • 基于文件的路由生成

  • 类型安全的 JSON 优先搜索参数状态管理 API

  • 路径和搜索参数模式验证

  • 搜索参数导航 API

  • 自定义搜索参数解析器/序列化器支持

  • 搜索参数中间件

  • 路由匹配/加载中间件

1.2. 基础使用示例

import React, { StrictMode } from 'react'
import ReactDOM from 'react-dom/client'
import {Outlet,RouterProvider,Link,createRouter,createRoute,createRootRoute} from '@tanstack/react-router'import { TanStackRouterDevtools } from '@tanstack/router-devtools'const rootRoute = createRootRoute({component: () => (<><div className="p-2 flex gap-2"><Link to="/" className={[&.active]:font-bold">Home</Link>{' '}<Link to="/about" className={[&.active]:font-bold">About</Link></div><hr /><Outlet /><TanStackRouterDevtools /></>),
})const indexRoute = createRoute({getParentRoute: () => rootRoute,path: '/',component: function Index() {return (<div className="p-2"><h3>Welcome Home!</h3></div>)},
})const aboutRoute = createRoute({getParentRoute: () => rootRoute,path: '/about',component: function About() {return <div className="p-2">Hello from About!</div>},
})const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])
const router = createRouter({ routeTree })declare module '@tanstack/react-router' {interface Register {router: typeof router}
}const rootElement = document.getElementById('app')!
if (!rootElement.innerHTML) {const root = ReactDOM.createRoot(rootElement)root.render(<StrictMode><RouterProvider router={router} /></StrictMode>,)
}

1.3. 原理浅析

@tanstack/router 的实现原理与 react-router 类似,关注的概念也完全相同,可以理解为它站在 react-router 的肩膀上,在某些细节上做了增强。

历史记录的实现:https://github.com/TanStack/router/blob/main/packages/history/src/index.ts

Router 入口:https://github.com/TanStack/router/blob/main/packages/react-router/src/link.tsx

2. wouter

2.1. 主要特性

  • 最小依赖,压缩后仅 2.1 KB,对比 React Router 的 18.7 KB。

  • 同时支持 React 和 Preact。

  • 没有顶级的 <Router /> 组件,它是完全可选的。

  • 模仿 React Router 的最佳实践,提供熟悉的 Route、Link、Switch 和 Redirect 组件。

  • 拥有基于 hook 的 API,用于更细粒度地控制路由:useLocation、useRoute 和 useRouter。

2.2. 基础使用示例

import { Link, Route, Switch } from "wouter";const App = () => (<><Link href="/users/1">Profile</Link><Route path="/about">About Us</Route>{/* Routes below are matched exclusively - the first matched route gets rendered*/}<Switch><Route path="/inbox" component={InboxPage} /><Route path="/users/:name">{(params) => <>Hello, {params.name}!</>}</Route>{/* Default route in a switch */}<Route>404: No such page!</Route></Switch></>
);

2.3. 原理浅析

对于不同路由历史与定位信息的封装。

  • https://github.com/molefrog/wouter/blob/v3/packages/wouter/src/use-browser-location.js

  • https://github.com/molefrog/wouter/blob/v3/packages/wouter/src/use-hash-location.js

  • https://github.com/molefrog/wouter/blob/v3/packages/wouter/src/memory-location.js

import { parse as parsePattern } from "regexparam";
import {useBrowserLocation,useSearch as useBrowserSearch,
} from "./use-browser-location.js";
import {useRef,useContext,createContext,isValidateElement,cloneElement,createElement as h,Fragment,forwardRef,useIsomorphicLayoutEffect,useEvent,
} from "./react-deps.js";
import { absolutePath, relativePath, unescape, stripQm } from "./paths.js";// 定义默认的 Router 对象
const defaultRouter = {hook: useBrowserLocation,searchHook: useBrowserSearch,parser: parsePattern,base: "",ssrPath: undefined,ssrSearch: undefined,hrefs: (x) => x,
};// 创建一个 Router 上下文,提供给应用中的其他部分使用
const RouterCtx = createContext(defaultRouter);// 获取最近的父级 router
export const useRouter = () => useContext(RouterCtx);// 创建一个参数上下文,提供给 `useParams()` 使用,以获取匹配的参数
const ParamsCtx = createContext({});
export const useParams = () => useContext(ParamsCtx);// 内部版本的 useLocation 函数,避免多余的 useRouter 调用
const useLocationFromRouter = (router) => {const [location, navigate] = router.hook(router);return [unescape(relativePath(router.base, location)),useEvent((to, navOpts) => navigate(absolutePath(to, router.base), navOpts)),];
};// 使用 useRouter 获取当前的 location
export const useLocation = () => useLocationFromRouter(useRouter());// 获取当前搜索参数并返回
export const useSearch = () => {const router = useRouter();return unescape(stripQm(router.searchHook(router)));
};// 路由匹配函数
export const matchRoute = (parser, route, path, loose) => {const { pattern, keys } =route instanceof RegExp? { keys: false, pattern: route }: parser(route || "*", loose);const result = pattern.exec(path) || [];const [base, ...matches] = result;return base !== undefined? [true,() => {const groups =keys !== false? Object.fromEntries(keys.map((key, i) => [key, matches[i]])): result.groups;let obj = { ...matches };groups && object.assign(obj, groups);return obj;},...(loose ? [$base] : []),]: [false, null];
};// 使用 useRouter 获取路由,并匹配路径
export const useRoute = (pattern) =>matchRoute(useRouter().parser, pattern, useLocation()[0]);// Router 组件,用于提供自定义路由上下文
export const Router = ({ children, ...props }) => {const parent_ = useRouter();const parent = props.hook ? defaultRouter : parent_;let value;const [path, search] = props.ssrPath?.split("?") ?? [];if (search) (props.ssrSearch = search), (props.ssrPath = path);props.hrefs = props.hrefs ?? props.hook?.hrefs;let ref = useRef({}),prev = ref.current,next = prev;for (let k in parent) {const option =k === "base"? parent[k] + (props[k] || ""): props[k] || parent[k];if (prev === next && option !== next[k]) {ref.current = next = { ...next };}next[k] = option;if (option !== parent[k]) value = next;}return h(RouterCtx.Provider, { value, children });
};// 渲染 Route 组件,根据 props 提供不同渲染逻辑
const h_route = ({ children, component }, params) => {if (component) return h(component, { params });return typeof children === "function" ? children(params) : children;
};// Route 组件,用于匹配路径并渲染对应组件
export const Route = ({ path, nest, match, ...renderProps }) => {const router = useRouter();const [location] = useLocationFromRouter(router);const [matches, params, base] =match ?? matchRoute(router.parser, path, location, nest);if (!matches) return null;const children = base? h(Router, { base }, h_route(renderProps, params)): h_route(renderProps, params);return h(ParamsCtx.Provider, { value: params, children });
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/pingmian/84954.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

VINS-Fusion 简介、安装、编译、数据集/相机实测

目录 VINS-Fusion 简介 安装 VINS-Fusion 源码安装 运行数据集 双目模式 单目IMU 模式 双目IMU 模式 D455 相机实际运行 双目IMU 模式 VINS-Fusion 简介 VINS-Fusion 是继 VINS-Mono 和 VINS-Mobile&#xff08;单目视觉惯导 SLAM 方案&#xff09;后&#xff0c;香港科 技大学…

SQL Developer 表复制

SQL Developer 表复制 此方法在数据量比较大时&#xff0c;比一条一条的insert要快得多&#xff1b;具体是会覆盖掉原数据&#xff0c;还是增量的处理&#xff0c;请自行创建demo表测试一下。 注意&#xff1a;原库版本要与目标库数据库版本一致&#xff0c;否则可能会报错的。…

影视剧学经典系列-梁祝-《吕氏春秋·应同》

1、背景 07版电视剧《梁山伯与祝英台》中&#xff0c;谢道韫作为先生&#xff0c;给学生讲了其中的句子。 2、名言 君为尊&#xff0c;以白为黑&#xff0c;臣不能从&#xff1b;父虽亲&#xff0c;以黑为白&#xff0c;子不能从”出自《吕氏春秋应同》 其意为&#xff0c;…

异步爬虫---

代码结构分析 这是一个同步新闻爬虫程序&#xff0c;主要包含以下几个部分&#xff1a; 们把爬虫设计为一个类&#xff0c;类在初始化时&#xff0c;连接数据库&#xff0c;初始化logger&#xff0c;创建网址池&#xff0c;加载hubs并设置到网址池。 爬虫开始运行的入口就是r…

微服务架构中的 Kafka:异步通信与服务解耦(二)

三、Kafka 基础入门 3.1 Kafka 是什么 Kafka 最初由 LinkedIn 公司开发&#xff0c;是一个开源的分布式事件流平台&#xff0c;后成为 Apache 基金会的顶级项目 。它不仅仅是一个简单的消息队列&#xff0c;更是一个分布式流处理平台&#xff0c;具备强大的消息队列、存储系统…

Lighthouse与首屏优化

之前提到首屏优化&#xff0c;想到的就是Vue项目首页打开很慢需要优化。一般都是肉眼看看&#xff0c;对当前的加载速度并没有一个准确的衡量标准&#xff0c;也没有很清晰的解决思路。 前两天我想给自己的网站申请谷歌广告&#xff0c;听说审核对网站的性能要求很高。于是网上…

Maven 之 打包项目时没有使用本地仓库依赖问题

背景 pom 中使用了第三方jar包&#xff0c;远程仓库设置的是阿里云&#xff0c;之前运行很好&#xff0c;今天不知道怎么的&#xff0c;打包总是报错&#xff0c;阿里云仓库无法找到依赖包(本来也没有)&#xff0c;按理来说&#xff0c;编译打包时会优先选择本地仓库的包才对&a…

Mysql基础入门\期末速成

DDL 操作数据库语句 创建&删除数据库语句 创建数据库 create database 数据库名称; -- 直接创建 create database if not exists 数据库名称; -- 如果不存在&#xff0c;则创建 create database 数据库名称 default charset utf8mb4; -- 创建编译类型utf8的数据类型 cre…

SCADA|KingSCADA4.0中历史趋势控件与之前版本的差异

哈喽,你好啊,我是雷工! 最近用到KingSCADA4.0信创版本,也算尝鲜使用。 在使用的过程中发现有些功能或多或少存在一些差异, 这里将遇到的一些不同总结一下,便于后期更好的使用。 01 历史趋势控件 在KingSCADA中有一个历史趋势曲线控件KSHTrend。 该控件既可以连接King…

ubuntu 拒绝ssh连接,连不上ssh,无法远程登录: Connection failed.

目录 问题描述视窗 可视化桌面命令行 问题描述 [C:\~]$ Connecting to 192.166.8.85:22... Could not connect to 192.166.8.85 (port 22): Connection failed.Type help to learn how to use Xshell prompt. [C:\~]$ Connecting to 192.166.8.85:22... Could not connect to …

【大模型应用开发】向量数据库向量检索方法存在问题及优化

一、检索结果重复 1. 问题分析 在构建向量数据库时&#xff0c;对文档分割会存在重复块&#xff08;chunk_overlap&#xff1a;指两个块之间共享的字符数量&#xff0c;用于保持上下文的连贯性&#xff0c;避免分割丢失上下文信息&#xff09;&#xff0c;如下图所示&#xf…

MySQL常用函数详解之数值函数

MySQL常用函数详解之数值函数 一、数值函数概述1.1 数值函数的作用1.2 数值函数分类 二、算术运算函数2.1 加法运算&#xff08;&#xff09;2.2 减法运算&#xff08;-&#xff09;2.3 乘法运算&#xff08;*&#xff09;2.4 除法运算&#xff08;/ 或 DIV&#xff09;2.5 取模…

13、Redis进阶二之Redis数据安全性分析

⼀ 、Redis性能压测脚本介绍 Redis的所有数据是保存在内存当中的&#xff0c; 得益于内存⾼效的读写性能&#xff0c; Redis的性能是⾮常强悍的 。但 是&#xff0c;内存的缺点是断电即丢失&#xff0c;所以 &#xff0c;在实际项⽬中&#xff0c; Redis—旦需要保存—些重要的…

【系统分析师】2011年真题:综合知识-答案及详解

文章目录 【第1题】【第2~3题】【第4~5题】【第6题】【第7~8题】【第9题】【第10题】【第11题】【第12题】【第13题】【第14题】【第15题】【第16题】【第17题】【第18题】【第19~20题】【第21题】【第22题】【第23题】【第24~25题】【第26题】【第27题】【第28题】【第29题】【…

FastAPI-MCP构建自定义MCP工具实操指南

一、简介 • FastAPI-MCP是一个基于python FastAPI框架开发的开源项目&#xff0c;可以自动识别并暴露FastAPI接口为MCP工具 • 拥有FastAPI框架的所有优点&#xff0c;如异步高并发、独立远程部署、OpenAPI文档 • 提供SSE、mcp-remote接入方式&#xff0c;支持设置授权访问…

LLMs之Memory:《LLMs Do Not Have Human-Like Working Memory》翻译与解读

LLMs之Memory&#xff1a;《LLMs Do Not Have Human-Like Working Memory》翻译与解读 导读&#xff1a;该论文通过三个精心设计的实验&#xff0c;证明了当前的大型语言模型&#xff08;LLMs&#xff09;缺乏类似人类的工作记忆。实验结果表明&#xff0c;LLMs无法在没有明确外…

Node.js验证码:从生成到验证的趣味之旅

文章目录 Node.js验证码&#xff1a;从生成到验证的趣味之旅&#x1f4dc; 引言&#xff1a;为什么需要验证码&#xff1f;1. 验证码的基本原理 &#x1f9e0;验证码工作流程示意图 2. 技术栈准备 &#x1f6e0;️3. 验证码生成详解 &#x1f3a8;3.1 生成SVG验证码3.2 转换为P…

芯科科技携最新Matter演示和参考应用精彩亮相Matter开放日和开发者大会

全面展示赋能Matter设备实现跨协议和跨海内外生态的技术能力 作为Matter标准创始厂商之一和其解决方案的领先供应商&#xff0c;Silicon Labs&#xff08;亦称“芯科科技”&#xff09;于6月12至13日参加由连接标准联盟中国成员组&#xff08;CMGC&#xff09;主办的Matter年度…

AndroidStudio下载的SDK没有tool目录,或者想要使用uiautomatorviewer工具

1.如果没有tool目录可以使用下面的地址进行下载 https://dl.google.com/android/repository/tools_r25.2.5-windows.zip 2.并且把下载的文件解压到放在AndroidStudio的目录中 3.如果使用uiautomatorviewer.bat出现下面的错误 Unable to connect to adb.Check if adb is instal…

FastJSON等工具序列化特殊字符时会加转义字符\

在Java中JSON数据格式用String接收时&#xff0c;此时在FastJSON层面看来该JSON只是普通字符串&#xff0c;所以对原字符串序列化会得到转义字符\ 得到转义后字符串&#xff0c;再反序列化转义后字符串会得到原字符串 String json"{\"name\": \"张三\&quo…