Javascript 文本内容不匹配。反应16中的警告

Javascript 文本内容不匹配。反应16中的警告,javascript,reactjs,express,webpack,webpack-dev-server,Javascript,Reactjs,Express,Webpack,Webpack Dev Server,我正在尝试使用服务器端渲染构建ReactJs应用程序 我的客户端和服务器入口点: const store = createStore(window.__INITIAL_STATE__); hydrate( <Provider store={store}> <BrowserRouter>{renderRoutes(routes)}</BrowserRouter> </Provider>, document.querySelec

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

const store = createStore(window.__INITIAL_STATE__);

hydrate(
  <Provider store={store}>
    <BrowserRouter>{renderRoutes(routes)}</BrowserRouter>
  </Provider>,
  document.querySelector('#root')
);
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>
      )
  );
});
const store=createStore(窗口、初始状态);
水合物(
{renderRoutes(routes)}
,
document.querySelector(“#root”)
);

const store = createStore(window.__INITIAL_STATE__);

hydrate(
  <Provider store={store}>
    <BrowserRouter>{renderRoutes(routes)}</BrowserRouter>
  </Provider>,
  document.querySelector('#root')
);
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>
      )
  );
});
const-app=express();
如果(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'));
应用程序使用(
webpackDevMiddleware(编译器{
publicPath:config.output.publicPath,
统计信息:“仅限错误”,
})
);
}
应用程序获取(“*”,(请求,请求)=>{
const helmet=helmet.renderStatic();
const htmlAttrs=helmet.htmlAttributes.toComponent();
const bodyAttrs=helmet.bodyAttributes.toComponent();
const context={};
常量数据={};
res.set('content-type','text/html');
res.send(
'' +
渲染字符串(
{helmet.title.toComponent()}
{helmet.meta.toComponent()}
{helmet.link.toComponent()}
{renderRoutes(routes)}
)
);
});
和组成部分:

home.jsx

import React, { Component } from 'react';

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

export default Home;
import React,{Component}来自'React';
类Home扩展组件{
render(){
回家;
}
}
导出默认主页;
当我在我的组件
Home
中更改并刷新浏览器页面时,我收到以下错误:

警告:文本内容不匹配。服务器:“主页”客户端:“主页1”


这是可以的,因为服务器渲染我的代码的旧版本。如何在服务器上重新加载代码,使客户端和服务器版本相同?

这里的问题是服务器端应用程序不反映代码更改。要做到这一点,您必须将express应用程序配置为网页条目

简单地说,您需要2个网页包配置,一个用于服务器,另一个用于客户端代码。 服务器1看起来像这样

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

这里详细解释了如何对发现此错误的用户执行此操作,因为您的客户端和服务器故意呈现不同的内容(例如服务器呈现的黑色主题在加载时被用户首选项替换),请使用
suppressionWarning
来抑制此错误

例如:

<div suppressHydrationWarning>Ignore this</div>
忽略此选项

我遇到了一个非常类似的错误-在服务器中使用staticRouter,在客户端使用browserRouter。我有很多路由,当我直接访问其中一个路由时(即,不通过客户端路由),它可以工作,但会出现JS错误。本文可能会提供帮助:有一个部分存在相同的错误-只需在页面上找到“文本内容不匹配”即可查看。感谢这一帮助,它非常简单=D,谢谢:D