样式组件在第一次增量静态再生后不起作用
styled-components doesn't work after the first Incremental Static Regeneration
我有这个 Next.Js 页面,每 1 秒重新验证一次:
import styled from 'styled-components';
export const getStaticProps = async () => {
return {
props: {},
revalidate: 1,
};
};
const Container = styled.div`
color: red;
font-size: 100px;
`;
const Shop = () => {
return <Container>TEST TEST TEST TEST</Container>;
};
export default Shop;
当我在我的托管服务提供商(共享托管 C 面板)上启动服务器时,我第一次访问该页面时,我得到了这个结果:
你可以看class的名字 name : BTSqf.
现在,当我刷新页面(服务器重新验证页面)时,我得到了这个结果:
可以看到class名字已经改成:cojIBn.
所以我的问题是如何在增量静态再生后保持页面的样式?
ps:当我将 Web Developer Tools 上的 class 名称 (cojIBn) 更改为原始名称 (BTSqf) 时,样式会恢复
在进行了一些额外的搜索之后,我找到了解决方案 blog Post
这是通过创建一个新的 'pages/_document.js' 文件并添加以下内容来解决的:
import Document, { Head, Html, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head></Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
我有这个 Next.Js 页面,每 1 秒重新验证一次:
import styled from 'styled-components';
export const getStaticProps = async () => {
return {
props: {},
revalidate: 1,
};
};
const Container = styled.div`
color: red;
font-size: 100px;
`;
const Shop = () => {
return <Container>TEST TEST TEST TEST</Container>;
};
export default Shop;
当我在我的托管服务提供商(共享托管 C 面板)上启动服务器时,我第一次访问该页面时,我得到了这个结果:
现在,当我刷新页面(服务器重新验证页面)时,我得到了这个结果:
可以看到class名字已经改成:cojIBn.
所以我的问题是如何在增量静态再生后保持页面的样式?
ps:当我将 Web Developer Tools 上的 class 名称 (cojIBn) 更改为原始名称 (BTSqf) 时,样式会恢复
在进行了一些额外的搜索之后,我找到了解决方案 blog Post
这是通过创建一个新的 'pages/_document.js' 文件并添加以下内容来解决的:
import Document, { Head, Html, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head></Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}