我正在学习如何在服务器上渲染我的React站点。到目前为止,我已经成功地使用异步数据进行了渲染,但在包含脚本时遇到了一个问题(因此,当我想拥有同构的应用程序时):
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;main (客户端)
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'))
});我确信一定是某个地方的小bug导致了这个错误,但我似乎找不到它。
发布于 2016-09-01 01:39:50
我猜客户端缺少正确呈现应用程序的状态。您需要将应用程序状态向下传递给客户端。这也被称为再水化。
您可以通过在服务器上序列化状态并将其作为JSON字符串与呈现的html一起发送来完成此操作。在客户端,您可以解析序列化的状态,并在创建store时将其用作初始状态。这将导致两个呈现,服务器和第一个客户端,产生相同的标记-->校验和等于。
选中可传递给createStore http://redux.js.org/docs/api/createStore.html的第二个参数
https://stackoverflow.com/questions/39251456
复制相似问题