React v15.0.0: Since that renderToString is deprecated, how to go about server-side rendering?

筅森魡賤 提交于 2019-12-14 02:57:48

问题


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:


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)


来源:https://stackoverflow.com/questions/36251454/react-v15-0-0-since-that-rendertostring-is-deprecated-how-to-go-about-server-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!