react 服務端渲染圖解

註解

服務端字符串化react應用
  const html = ReactDOMServer.renderToString(
    <Provider store={store}>
      <StaticRouter location={ctx.url} context={{}}>
        <App />
      </StaticRouter>
    </Provider>
  );
向html中注入store的方式
var htmlTemplate = `
  <!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"> ${content}</div>
    <script>window.__INITIAL_STATE__ =${JSON.stringify(initState)}</script>
    <script type="text/javascript" src="/static/js/main.js"></script>
</body>
</html>
`

客戶端創建store時,用window.__INITIAL_STATE__初始化store即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章