【发布时间】:2022-06-19 15:45:04
【问题描述】:
我正在尝试让 SSR 在我的应用中运行,但出现错误:
水化失败,因为初始 UI 与之前的不匹配 在服务器上渲染。
现场演示代码为here
问题的现场演示是here(打开开发工具控制台查看错误):
// App.js
import React from "react";
class App extends React.Component {
head() {
return (
<head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<title>React App</title>
</head>
);
}
body() {
return (
<body>
<div className="App">
<h1>Client says Hello World</h1>
</div>
</body>
);
}
render() {
return (
<React.Fragment>
{this.head()}
{this.body()}
</React.Fragment>
)
}
}
export default App;
// index.js
import React from "react";
import * as ReactDOM from "react-dom/client";
import { StrictMode } from "react";
import App from "./App";
// const container = document.getElementById("root");
const container = document.getElementsByTagName("html")[0]
ReactDOM.hydrateRoot(
container,
<StrictMode>
<App />
</StrictMode>
);
现场演示中显示的 Html 模板由后端提供,并使用以下代码生成:
const ReactDOMServer = require('react-dom/server');
const clientHtml = ReactDOMServer.renderToString(
<StrictMode>
<App />
</StrictMode>
)
// 将clientHtml 提供给客户端
我需要动态生成<head></head> and <body></body>部分,如App类所示
【问题讨论】:
标签: reactjs