React-router v7 第二章(路由模式)

路由模式

在React RouterV7 中,是拥有不同的路由模式,路由模式的选择将直接影响你的整个项目。React Router 提供了四种核心路由创建函数: createBrowserRoutercreateHashRoutercreateMemoryRoutercreateStaticRouter

1. createBrowserRouter(推荐)

核心特点:
  • 使用HTML5的history API (pushState, replaceState, popState)
  • 浏览器URL比较纯净 (/search, /about, /user/123)
  • 需要服务器端支持(nginx, apache,等)否则会刷新404
使用场景:
  • 大多数现代浏览器环境
  • 需要服务器端支持
  • 需要URL美观

2. createHashRouter

核心特点:
  • 使用URL的hash部分(#/search, #/about, #/user/123)
  • 不需要服务器端支持
  • 刷新页面不会丢失
使用场景:
  • 静态站点托管例如(github pages, netlify, vercel)
  • 不需要服务器端支持

3. createMemoryRouter

核心特点:
  • 使用内存中的路由表
  • 刷新页面会丢失状态
  • 切换页面路由不显示URL
使用场景:
  • 非浏览器环境例如(React Native, Electron)
  • 单元测试或者组件测试(Jest, Vitest)

4. createStaticRouter

核心特点:
  • 专为服务端渲染(SSR)设计
  • 在服务器端匹配请求路径,生成静态 HTML
  • 需与客户端路由器(如 createBrowserRouter)配合使用
使用场景:
  • 服务端渲染应用(如 Next.js 的兼容方案)
  • 需要SEO优化的页面

解决刷新404问题

当使用createBrowserRouter时,如果刷新页面会丢失状态,这是因为浏览器默认会去请求服务器上的资源,如果服务器上没有资源,就会返回404。 要解决这个问题就需要在服务器配置一个回退路由,当请求的资源不存在时,返回index.html

  • Nginx(推荐)

下载地址:Nginx

bash 复制代码
location / {
  try_files $uri $uri/ /index.html;
}
  • Apache
bash 复制代码
<IfModule mod_negotiation.c>
  Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
  • Vercel
json 复制代码
{
  "rewrites": [{ "source": "/:path*", "destination": "/index.html" }]
}
  • Nodejs
js 复制代码
const http = require('http')
const fs = require('fs')
const httpPort = 80

http
  .createServer((req, res) => {
    fs.readFile('index.html', 'utf-8', (err, content) => {
      if (err) {
        console.log('We cannot open "index.html" file.')
      }

      res.writeHead(200, {
        'Content-Type': 'text/html; charset=utf-8',
      })

      res.end(content)
    })
  })
  .listen(httpPort, () => {
    console.log('Server listening on: http://localhost:%s', httpPort)
  })
相关推荐
一个处女座的程序猿O(∩_∩)O8 分钟前
React 多组件状态管理:从组件状态到全局状态管理全面指南
前端·react.js·前端框架
鹏多多10 分钟前
用useTransition解决React性能卡顿问题+实战例子
前端·javascript·react.js
只愿云淡风清20 分钟前
ECharts地图数据压缩-ZigZag算法
前端·javascript·echarts
亿元程序员28 分钟前
都2025年了,还有面试问A*寻路的???
前端
Moment28 分钟前
Node.js v25.0.0 发布——性能、Web 标准与安全性全面升级 🚀🚀🚀
前端·javascript·后端
杨超越luckly33 分钟前
HTML应用指南:利用POST请求获取中国一汽红旗门店位置信息
前端·arcgis·html·数据可视化·门店数据
专注前端30年37 分钟前
【JavaScript】every 方法的详解与实战
开发语言·前端·javascript
速易达网络40 分钟前
Java Web登录系统实现(不使用开发工具)
java·开发语言·前端
IT_陈寒43 分钟前
Vite 3.0 性能优化实战:5个技巧让你的构建速度提升200% 🚀
前端·人工智能·后端
金士顿1 小时前
EC-Engineer SDK 核心 API 使用指南
前端