提问人:Yilmaz 提问时间:2/16/2020 更新时间:4/16/2021 访问量:1697
如何用 styled-components 水合反应 ssr
How to hydrate react ssr with styled-components
问:
我正在构建一个反应 ssr。我决定使用 styled-components for 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 应该采用的方式,但仍然出现此错误。这个话题有点混乱,希望有人能帮上忙。
答: 暂无答案
评论