我正在建立一个反应固态继电器。我决定为CSS使用样式化组件来尝试CSS-in-js。我在控制台上收到此错误:
react-dom.development.js:530 Warning: Prop `className` did not match. Server: "Home__StyledHome-s26o42-0 frotjg" Client: "Home__StyledHome-s26o42-0 kCdWHN"
注意:我根本没有使用“ className”。
我点击了“ react-dom.development.js:530”,并指向了这一行
Function.prototype.apply.call(console.error, console, argsWithFormat);
这是服务器端渲染器函数,我们在其中渲染html:
import { ServerStyleSheet, StyleSheetManager } from "styled-components";
export default (req, store, context) => {
const sheet = new ServerStyleSheet();
try {
const content = renderToString(
<Provider store={store}>
<StaticRouter location={req.path} context={context}>
<StyleSheetManager sheet={sheet.instance}>
<div>{renderRoutes(Routes)}</div>
</StyleSheetManager>
</StaticRouter>
</Provider>
);
const styleTags = sheet.getStyleTags();
const helmet = Helmet.renderStatic();
return `
<html>
<head>
${helmet.title.toString()}
${helmet.meta.toString()}
${styleTags}
</head>
<body>
<div id="root">${content}</div>
<script>window.INITIAL_STATE=${serialize(store.getState())}</script>
<script src="bundle.js"> </script>
</body></html> `;
} catch (e) {
console.log(e);
} finally {
sheet.seal();
}
};
这是客户端的水合功能:
import { ServerStyleSheet } from "styled-components";
//StyleSheetManager: documentation says do not use in the client side.
const sheet = new ServerStyleSheet();
ReactDOM.hydrate(
<Provider store={store}>
<BrowserRouter>
<div>{renderRoutes(Routes)}</div>
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
因为这不起作用,所以我实现了它,但它也不起作用: 服务器端:
export default (req, store, context) => {
const sheet = new ServerStyleSheet();
try {
const content = renderToString(
sheet.collectStyles(
<Provider store={store}>
<StaticRouter location={req.path} context={context}>
<div>{renderRoutes(Routes)}</div>
</StaticRouter>
</Provider>
)
);
const styleTags = sheet.getStyleTags();
const helmet = Helmet.renderStatic();
return `
<html>
<head>
${helmet.title.toString()}
${helmet.meta.toString()}
${styleTags}
</head>
<body>
<div id="root">${content}</div>
<script>window.INITIAL_STATE=${serialize(store.getState())}</script>
<script src="bundle.js"> </script>
</body></html> `;
} catch (e) {
console.log("style-component server-site", e);
} finally {
sheet.seal();
}
};
客户端:
const sheet = new ServerStyleSheet();
ReactDOM.hydrate(
sheet.collectStyles(
<Provider store={store}>
<BrowserRouter>
<div>{renderRoutes(Routes)}</div>
</BrowserRouter>
</Provider>,
document.getElementById("root")
)
);
带有react-ssr的样式化组件的文档非常短。我实现了应该是API的方式,但仍然出现此错误。这个话题有点混乱,希望有人能帮忙。