【问题标题】:How to do server rendering with react-router 1.0.0?如何使用 react-router 1.0.0 进行服务器渲染?
【发布时间】:2016-01-27 08:14:27
【问题描述】:

我是 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)

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

【问题讨论】:

    标签: reactjs react-router


    【解决方案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

    【讨论】:

    • 谢谢。但是当我运行这些代码时,shell 会报错:renderToString(&lt;RoutingContext, SyntaxError: Unexpected token &lt;。我该如何解决这个问题?
    猜你喜欢
    • 2016-08-06
    • 2015-08-18
    • 2017-05-20
    • 2016-04-11
    • 2016-05-09
    • 2016-01-28
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多