React can be used on server side rendering. What does that mean?

故事扮演 提交于 2019-11-28 06:39:40

问题


I am new to React and Redux . Although i know that React is just a view layer . But i saw a term "React can be used on server side rendering". What does this mean and how it works behind the scene with nodejs.Can anyone help me in getting clear the fact that "What is server side render in react".


回答1:


The react-dom package includes a server module. This module allows you render your react application to a simple HTML string with reactDOMServer.renderTostring(). Basically a snapshot of your view for a given set of props:

https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring

Additionally this functions calculates a unique hash from the string it generated and appends it to the html. On the client side react can "pick up" the server generated HTML and use it as its "first render".

Though the client side first render and the server render need to produce the exact same output for react to pick it up on the client side. React can check this via the generated hash: The client side react will also generate a html string (without modifying the actual DOM, I think this is done only on the virtual DOM). Now it can also calculate a hash from its virtual DOM and compare it with the server rendered one. If they match, no rendering needs be done. If they don't, the client side react will throw away the server generated DOM and replace it with its version (and print out an error/warning).

In combination with redux this means in addition to rendering the HTML you need to pass down the state of your store (store.getState()) to the client. The client can then use this serialized state as an initial state when creating its instance of the redux store. This will lead to both renders (client + server) to match up.

If you don't need the client side to do anything and just want to create static markup on the server side, react-dom offers a renderToStaticMarkup() function:

https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup



来源:https://stackoverflow.com/questions/39466316/react-can-be-used-on-server-side-rendering-what-does-that-mean

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