【问题标题】:Text content did not match. Warning in React 16文本内容不匹配。 React 16 中的警告
【发布时间】:2018-05-01 03:54:18
【问题描述】:

我尝试使用服务器端渲染构建 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 并刷新浏览器页面时,我收到此错误:

警告:文本内容不匹配。服务器:“home” 客户端:“home1”

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

【问题讨论】:

  • 我遇到了一个非常相似的错误 - 在服务器中使用 staticRouter 在客户端中使用 browserRouter。我有一堆路由,当我直接访问其中一个路由(即不通过客户端路由)时,它可以工作,但会出现 JS 错误。
  • 这篇文章可以帮上忙:tylermcginnis.com/react-router-server-rendering 有一个部分出现了同样的错误 - 只需在页面上找到“文本内容不匹配”即可查看。

标签: javascript reactjs express webpack webpack-dev-server


【解决方案1】:

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

例如:

<div suppressHydrationWarning>Ignore this</div>

【讨论】:

  • 谢谢这个帮助我,这很简单=D,谢谢:D
【解决方案2】:

这里的问题是您的服务器端应用程序没有反映代码更改。为此,您必须将您的 express 应用配置为 webpack 条目。

简而言之,您需要 2 个 webpack 配置,一个用于服务器,另一个用于客户端代码。 服务器看起来像这样

module.exports = {
  entry: {
    server: './server.js',
  },
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].js'
  },
  target: 'node',
  node: {
    // Need this when working with express, otherwise the build fails
    __dirname: false,   // if you don't put this is, __dirname
    __filename: false,  // and __filename return blank or /
  },
  externals: [nodeExternals()], // Need this to avoid error when working with Express
  module: {
    rules: [
      {
        // Transpiles ES6-8 into ES5
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        // Loads the javacript into html template provided.
        // Entry point is set below in HtmlWebPackPlugin in Plugins 
        test: /\.html$/,
        use: [{loader: "html-loader"}]
      }
    ]
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./index.html",
      filename: "./index.html",
      excludeChunks: [ 'server' ]
    })
  ]
}

这是nice article 详细解释如何做到这一点

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 2019-05-26
    • 2018-03-08
    • 2022-12-05
    • 1970-01-01
    • 2016-12-06
    • 2018-11-14
    • 2021-11-26
    相关资源
    最近更新 更多