我尝试使用服务器端渲染构建 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>
)
);
});
和组件:
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/