当前位置: 移动技术网 > IT编程>网页制作>CSS > ReactRouter服务端渲染教程

ReactRouter服务端渲染教程

2018年04月09日  | 移动技术网IT编程  | 我要评论

服务端渲染

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

发生错误时发送一个500的响应

需要重定向时发送一个30x的响应

在渲染之前获得数据 (用 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())
    } else {
      res.send(404, 'Not found')
    }
  })
})

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网