开发指南 开发指南
React Router 中文文档
TypeScript 中文文档
gitee (opens new window)
React Router 中文文档
TypeScript 中文文档
gitee (opens new window)
  • 首页
  • 1、简介
  • 2、基础
    • 路由配置
    • 路由匹配原理
    • History
    • 默认路由(IndexRoute)与 IndexLink
  • 3、高级用法
    • 动态路由
    • 跳转前确认
    • 服务端渲染
    • 组件生命周期
    • 组件外部跳转
  • 4、升级指南
  • 5、排错
  • 6、API文档
  • 7、词汇表

# 服务端渲染

服务端渲染与客户端渲染有些许不同,因为你需要:

  • 发生错误时发送一个 500 的响应
  • 需要重定向时发送一个 30x 的响应
  • 在渲染之前获得数据 (用 router 帮你完成这点)

为了迎合这一需求,你要在 <Router> API 下一层使用:

  • 使用 match 在渲染之前根据 location 匹配 route
  • 使用 RoutingContext 同步渲染 route 组件

它看起来像一个虚拟的 JavaScript 服务器:

import { renderToString } from 'react-dom/server'
import { match, RoutingContext } from 'react-router'
import routes from './routes'

serve((req, res) => {
  // 注意!这里的 req.url 必须是原始请求的全路径URL,包括参数字段
  match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if (error) {
      res.send(500, error.message)
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    } else if (renderProps) {
      res.send(200, renderToString(<RoutingContext {...renderProps} />))
    } else {
      res.send(404, 'Not found')
    }
  })
})

至于加载数据,你可以用 renderProps 去构建任何你想要的形式——例如在 route 组件中添加一个静态的 load 方法,或如在 route 中添加数据加载的方法——由你决定。

← 跳转前确认 组件生命周期 →

内容转载自开源项目React Router中文文档
React Router 中文文档 | 赣公网安备 36012102000277号 | 赣ICP备2021002441号-2