问题
I was trying to understand what's the difference between ReactDOMServer.renderToString()
and ReactDOMServer.renderToStaticMarkup()
on React 16.8.6.
This is what I understood:
renderToStaticMarkup()
is used on the server side when you just want to render the markup and don't want to hydrate it on the client side. (https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup)renderToString()
is used on the server side when you want to use theReactDOM.hydrate()
function to hydrate the application on the client side. (https://reactjs.org/docs/react-dom-server.html#rendertostring)
So, if I'm right, the only difference between this two methods is that renderToString()
adds the data-reactroot
on the main element of the application. React reinforces this on the renderToStaticMarkup()
documentation:
Similar to renderToString, except this doesn’t create extra DOM attributes that React uses internally, such as data-reactroot. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.
If you plan to use React on the client to make the markup interactive, do not use this method. Instead, use renderToString on the server and ReactDOM.hydrate() on the client.
But, I was reading this issue on React's repository where Dan Abramov said:
Instead, use hydrate() to explicitly tell React to hydrate existing HTML. Then it won't depend on whether data-reactroot exists or not.
And:
...The suggested migration path is to use ReactDOM.hydrate() which completely sidesteps the problem because it doesn't rely on the data-reactroot attribute.
So, my question is: Is data-reactroot relevant to the hydrate function in React or is the documentation wrong?
Understanding this will be really helpful to fix a bug I'm having while hydration.
来源:https://stackoverflow.com/questions/57787670/is-data-reactroot-relevant-to-the-hydrate-function-in-react