What's the difference between hydrate() and render() in React 16?

后端 未结 6 940
我寻月下人不归
我寻月下人不归 2021-01-30 05:53

I\'ve read the documentation, but I didn\'t really understand the difference between hydrate() and render() in React 16.

I know hydrate()

6条回答
  •  情书的邮戳
    2021-01-30 06:48

    I don't have anything specific to add to what's been said above about the use of hydrate, but in trying to learn about it I put together a little example, so here's the work for whoever finds it helpful.

    Goal

    Serve two pages, one which uses ReactDOM.hydrate and one which uses ReactDOM.render. They will depend upon some react components written in JSX, which are loaded by

    ${ reactDOMMethod }

    ${ reactElementString }
    hydrate render `; }

    Finally, the actual server

    // server.js
    
    let http = require('http');
    let fs   = require('fs');
    
    let renderPage       = fs.readFileSync('render.html');
    let hydratePage      = fs.readFileSync('hydrate.html');
    let componentsSource = fs.readFileSync('components.js');
    
    http.createServer((req, res) => {
      if (req.url == '/components.js') {
        // artificial delay
        setTimeout(() => {
        res.setHeader('Content-Type','text/javascript');
        res.end(componentsSource);
        }, 2000);
      } else if (req.url == '/render.html') {
        res.end(renderPage);
      } else {
        res.end(hydratePage);
      }
    }).listen(80,'127.0.0.1');
    

提交回复
热议问题