2016-08-21 39 views
2

在服務器端渲染中,結構是否需要我們渲染應用兩次?在如下所示的server.js文件中,應用程序結構被呈現併發送到客戶端。雖然完整代碼已由生成Server.js,Client.js通過調用render函數再次執行此操作。ReactJS爲服務器端呈現的應用渲染應用兩次嗎? (DUPLICATE CODE)

因此該應用的最終結構,正如我理解它是: SERVER.js(呈現HTML,獲取初始狀態,並將其設置在PRELOADED_STATE變量,使用renderFullPage函數呈現頁面) ==> CLIENT.js(渲染使用PRELOADED_STATE varible

請糾正我,如果我錯了,在App strucutre。如果沒有,我們不能僅僅做一次?

Server.js

import path from 'path' 
import Express from 'express' 
import React from 'react' 
import { createStore } from 'redux' 
import { Provider } from 'react-redux' 
import counterApp from './reducers' 
import App from './containers/App' 
import { renderToString } from 'react-dom/server' 

const app = Express() 
const port = 3000 

// This is fired every time the server side receives a request 
app.use(handleRender) 

// We are going to fill these out in the sections to follow 
function handleRender(req, res) { /* ... */ } 
function renderFullPage(html, preloadedState) { /* ... */ } 

app.listen(port) 

function handleRender(req, res) { 
    // Create a new Redux store instance 
    const store = createStore(counterApp) 

    // Render the component to a string 
    const html = renderToString(
    <Provider store={store}> 
     <App /> 
    </Provider> 
) 

    // Grab the initial state from our Redux store 
    const preloadedState = store.getState() 

    // Send the rendered page back to the client 
    res.send(renderFullPage(html, preloadedState)) 
} 
function renderFullPage(html, preloadedState) { 
    return ` 
    <!doctype html> 
    <html> 
     <head> 
     <title>Redux Universal Example</title> 
     </head> 
     <body> 
     <div id="root">${html}</div> 
     <script> 
      window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)} 
     </script> 
     <script src="/static/bundle.js"></script> 
     </body> 
    </html> 
    ` 
} 

Client.js

import React from 'react' 
import { render } from 'react-dom' 
import { createStore } from 'redux' 
import { Provider } from 'react-redux' 
import App from './containers/App' 
import counterApp from './reducers' 

// Grab the state from a global injected into server-generated HTML 
const preloadedState = window.__PRELOADED_STATE__ 

// Create Redux store with initial state 
const store = createStore(counterApp, preloadedState) 

render(
    <Provider store={store}> 
    <App /> 
    </Provider>, 
    document.getElementById('root') 

回答

1

答案取決於你的意思與渲染兩倍。 React將比較服務器中生成的節點的數據校驗和與虛擬DOM中生成的節點的數據校驗和,以驗證它們與客戶端中生成的相同。這樣就不需要修改DOM,只需要修改虛擬DOM。

official React documentation

如果你已經有這個服務器呈現標記一個節點上調用ReactDOM.render(),陣營將保留它,只重視事件處理程序,讓您有一個非常高性能的首次加載體驗。

編輯:我錯誤地寫道,要比較的數據是reactId而不是校驗和。

相關問題