2016-08-31 55 views
0

我正在学习如何在服务器上呈现我的React站点。到目前为止,我已经成功地做到与异步数据的渲染,但我有一个问题,当我包括脚本(ERGO,我想有同构的应用程序):同构反应 - 校验和不匹配

Warning: React attempted to reuse markup in a container but the checksum was invalid (...): 
(client) <!-- react-empty: 1 - 
(server) <div class="blah" dat 

我想不通为什么正在发生。我的代码如下:

服务器

require('babel-register'); 

import express from 'express'; 
import path from 'path'; 

import React from 'react'; 
import { renderToString } from 'react-dom/server' 
import { match } from 'react-router' 
import { ReduxAsyncConnect, loadOnServer, reducer as reduxAsyncConnect } from 'redux-connect' 
import { Provider } from 'react-redux'; 

import routes from './app/routes'; 
import store from './app/store'; 

const app = express(); 
const port = 3100; 

const createPage = (html) => { 
    return `<!doctype html> 
    <html> 
     <head> 
     <title>123</title> 
     </head> 
     <body> 
     <div id="app">${html}</div> 

     <script src="/public/index.js"></script> 
     </body> 
    </html>` 
}; 

app.get('/', (req, res) => { 
    match({ routes, location: req.url }, (err, redirect, renderProps) => { 
    loadOnServer({ ...renderProps, store }).then(() => { 
     const appHTML = renderToString(
     <Provider store={store} key="provider"> 
      <ReduxAsyncConnect {...renderProps} /> 
     </Provider> 
    ); 

     const html = createPage(appHTML); 
     res.send(html); 
    }).catch((e) => { console.log(e); }) 
    }) 
}); 

app.use('/public', express.static(path.join(__dirname, 'public'))); 
app.use('/data', express.static(path.join(__dirname, 'data'))); 

app.listen(port); 
console.log(`localhost:${port}`); 

路线:

import React from 'react'; 
import { Router, Route, browserHistory } from 'react-router'; 
import { ReduxAsyncConnect, asyncConnect, reducer as reduxAsyncConnect } from 'redux-connect' 
import App from './Components/App'; 
import { Provider } from 'react-redux'; 

import store from './store'; 

const routes = (
    <Provider store={store} key="provider"> 
    <Router render={(props) => <ReduxAsyncConnect {...props} />} history={browserHistory}> 
     <Route path="/" component={App}/> 
    </Router> 
    </Provider> 
); 

export default routes; 

主(客户端)

import React from 'react'; 
import { render } from 'react-dom'; 
import routes from './routes'; 
import { match } from 'react-router' 

match({ routes, location: '/' },() => { 
    render(routes, document.getElementById('app')) 
}); 

我敢肯定,有一个小错误的地方,产生这个错误,但我似乎无法找到它。

回答

1

我猜客户端缺少正确呈现应用程序的状态。您需要将应用程序状态传递给客户端。这也被称为补液。

您可以通过在服务器上序列化您的状态并将其作为JSON字符串与呈现的html发送下来来完成此操作。在客户端,您可以解析序列化状态,并在创建store时将其用作初始状态。这将导致呈现器(服务器和第一个客户端端)产生相同的标记 - >校验和等于。

检查第二个参数可以传递给createStore http://redux.js.org/docs/api/createStore.html

+1

我知道我失去了一些东西那么明显,谢谢! –