React v15.0.0: Since that renderToString is deprec

2019-08-09 10:29发布

There is a new release candidate of React, v 15.0.0. Since the renderToString method now is deprecated in the library, and apparently is going to be discontinued in future versions, what is the way to support server-side rendering with React in the new version?

On the docs page, no replacement for the renderToString or other explanation has been provided except that this particular method is no longer supported.

Thank you

1条回答
欢心
2楼-- · 2019-08-09 10:48

As described in the comments, the correct (and only) way to render to a string with recent versions of React is to use ReactDOMServer's renderToString. Lots of existing answers and documentation refer to the removed React.renderToString, though. It has been deprecated for a while, but apparently only removed recently.

A quick and dirty example of what this might look like (running with node-babel):

const Express = require('express')
const React = require('react')
const ReactDomServer = require('react-dom/server')

const Label = React.createClass({
  render: function () {
    return <p> Foo! </p>
  }
})

const server = Express()

server.use(function(req, res) {
  const appHtml = ReactDomServer.renderToString(<Label />)
  res.send(appHtml)
})

server.listen(3000)
查看更多
登录 后发表回答