javascript - 文本内容不匹配。 React 16 中的警告

标签 javascript reactjs express webpack webpack-dev-server

我尝试使用服务器端渲染构建 ReactJs 应用程序 我的客户端和服务器入口点:

client.jsx

const store = createStore(window.__INITIAL_STATE__);

hydrate(
  <Provider store={store}>
    <BrowserRouter>{renderRoutes(routes)}</BrowserRouter>
  </Provider>,
  document.querySelector('#root')
);

server.jsx

const app = express();

if (isDev) {
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const config = require('../../webpack.config.js');
  const compiler = webpack(config);

  app.use(express.static('/public'));
  app.use(
    webpackDevMiddleware(compiler, {
      publicPath: config.output.publicPath,
      stats: 'errors-only',
    })
  );
}

app.get('*', (req, res) => {
  const helmet = Helmet.renderStatic();
  const htmlAttrs = helmet.htmlAttributes.toComponent();
  const bodyAttrs = helmet.bodyAttributes.toComponent();

  const context = {};
  const data = {};

  res.set('content-type', 'text/html');

  res.send(
    '<!DOCTYPE html>' +
      renderToString(
        <html {...htmlAttrs}>
          <head>
            {helmet.title.toComponent()}
            {helmet.meta.toComponent()}
            {helmet.link.toComponent()}
          </head>
          <body {...bodyAttrs}>
            <div id="root">
              <StaticRouter location={req.url} context={context}>
                {renderRoutes(routes)}
              </StaticRouter>
            </div>
            <script
              dangerouslySetInnerHTML={{
                __html: `window.__INITIAL_STATE__ = ${JSON.stringify(data)}`,
              }}
            />
            <script src="/public/vendor.js" />
            <script src="/public/app.js" />
          </body>
        </html>
      )
  );
});

和组件:

home.jsx

import React, { Component } from 'react';

class Home extends Component {
  render() {
    return <div>home</div>;
  }
}

export default Home;

当我更改组件 Home 并刷新浏览器页面时,出现此错误:

Warning: Text content did not match. Server: "home" Client: "home1"

没关系,因为服务器呈现我的代码的旧版本。如何在服务器上重新加载代码,使客户端和服务器版本相等?

最佳答案

对于那些因为您的客户端和服务器故意呈现不同内容(例如服务器呈现深色主题,在加载时被用户偏好替换)而发现此错误的人,请使用 suppressHydrationWarning 来抑制错误。

例如:

<div suppressHydrationWarning>Ignore this</div>

关于javascript - 文本内容不匹配。 React 16 中的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47349500/

相关文章:

javascript - 获取相对于某些 div 的鼠标指针坐标

javascript - 单击排序按钮后数据不会重新呈现

reactjs - 当 ngrok 尝试连接到 React 开发服务器时,主机 header 无效

javascript - 如何处理这两个: onClick and onMouseMove for one dom element?

node.js - 通用错误处理程序 MEANJS、mongoose、winston

node.js - 如何使用 'has-many belongs-to relationaship' 访问 node.js 中的记录?

javascript - JS 和 CSS 动画的低帧率

javascript - node.js 全局变量使用?

javascript - editly - 创建视频后在哪里可以获得返回值?

javascript - 如何从下拉 react /redux更新产品列表