In React, OK to always call ReactDOM.hydrate instead of ReactDOM.render?

后端 未结 2 1771
南笙
南笙 2021-02-14 19:26

I\'ve got code like the following where I\'m calling ReactDOM.hydrate. This is shared code that sometimes gets called from the node server and sometimes in the cli

2条回答
  •  清酒与你
    2021-02-14 20:06

    hydrate do works similar to render on client side whether the HTML has server rendered markup or not, but when there is no markup previously like not SSR then hydrate produces some warnings but, it will render your markup as expected. A better way to solve this would be to check if its SSR (assuming root as your parent div id) :

    var isMarkupPresent = document.getElementById('root').hasChildNodes();
    

    and then you can either render or hydrate:

    isMarkupPresent ? hydrate(...) ? render(...)
    

提交回复
热议问题