React-SSR

2020-09-03  本文已影响0人  zhulichao

How to implement server-side rendering in your React app in three simple steps
React 服务端渲染从入门到精通

什么是服务端渲染

当用户或爬虫程序访问页面 URL 时,将组件或页面通过服务器生成 HTML 字符串,再发送到浏览器,最后将静态标记"混合"为客户端上完全交互的应用程序。服务端渲染只发生在首屏,在客户端处理后面的请求。

服务端渲染和客户端渲染的区别

可以组合使用这 2 种方式创建同构应用

如何在页面中快速判断是否为服务端渲染

在服务端渲染 React 的后果

什么时候应该使用服务端渲染

如何工作

// server rendered home page
app.get('/', (req, res) => {
  const { preloadedState, content } = ssr(initialState);
  const response = template('Server Rendered Page', preloadedState, content);
  res.setHeader('Cache-Control', 'assets, max-age=604800');
  res.send(response);
});
function ssr(initialState) {
  // Configure the store with the initial state provided
  const store = configureStore(initialState);

  // render the App store static markup ins content variable
  let content = renderToString(
    <Provider store={store}>
      <App />
    </Provider>
  );

  // Get a copy of store data to create the same store on client side
  const preloadedState = store.getState();

  return { content, preloadedState };
}
function template(title, initialState = {}, content = '') {
  // Dynamically ship scripts based on render type
  let scripts = '';
  if (content) {
    // 服务端渲染
    scripts = ` <script>
                   window.__STATE__ = ${JSON.stringify(initialState)}
                </script>
                <script src="assets/client.js"></script>
                `;
  } else {
    // 客户端渲染
    scripts = ` <script src="assets/bundle.js"> </script> `;
  }
  let page = `<!DOCTYPE html>
              <html lang="en">
              <head>
                <meta charset="utf-8">
                <title> ${title} </title>
                <link href="assets/style.css" rel="stylesheet">
              </head>
              <body>
                <div class="content">
                   <div id="app" class="wrap-inner">
                      <!--- magic happens here -->  ${content}
                   </div>
                </div>

                  ${scripts}
              </body>
              `;

  return page;
}
// client.js
import React from 'react';
import { hydrate } from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './redux/configureStore';
import App from './components/app';

// Read the state sent with markup
const state = window.__STATE__;

// delete the state from global window object
delete window.__STATE__;

// reproduce the store used to render the page on server
const store = configureStore(state);

/**
 * hydrate the page to make sure both server and client
 * side pages are identical. This includes markup checking,
 * react comments to identify elements and more.
 */

hydrate(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector('#app')
);
上一篇 下一篇

猜你喜欢

热点阅读