如何使用react-router 1.0.0进行服务器渲染?

时间:2015-10-27 18:43:57

标签: reactjs react-router

我是React的新手,并遵循构建同构应用程序的教程。在服务器端,它使用router.run()执行渲染操作,但它在react-router 1.0.0中被删除。

Router.run(routes, req.url, Handler => {
    let content = React.renderToString(<Handler />);
    res.render('index', {
        content: content
    });
});

更新指南所说的是

// v0.13.x
Router.run(routes, (Handler) => {
  render(<Handler/>, el);
})

// v1.0
render(<Router>{routes}</Router>, el)

但是如何处理服务器渲染呢?

1 个答案:

答案 0 :(得分:1)

示例:

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

serve((req, res) => {
  // Note that req.url here should be the full URL path from
  // the original request, including the query string.
  match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if (error) {
      res.status(500).send(error.message)
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    } else if (renderProps) {
      res.status(200).send(renderToString(<RoutingContext {...renderProps} />))
    } else {
      res.status(404).send('Not found')
    }
  })
})

可以找到更多in the docs