同构反应 - 校验和不匹配

Isomorphic React - checksum doesn't match

我正在学习如何在服务器上呈现我的 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;

主要(客户端)

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'))
});

我确定某个地方有一个小错误导致了这个错误,但我似乎找不到它。

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

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

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