【发布时间】:2021-09-15 13:11:15
【问题描述】:
我是 Next.js 的新手,并不完全了解缓存的功能。
给出以下简化示例:
根据当前分钟是偶数还是奇数,呈现组件 Test1 或 Test2 的索引页面:
import { Test2 } from '@src/components/test2'
import React from 'react'
const conditionallyChooseComponent = () => {
const d = new Date()
if (d.getMinutes() % 2 === 0) return <Test1 />
else return <Test2 />
}
export default function Home() {
return <div>{conditionallyChooseComponent()}</div>
}
并具有以下组件。测试1:
export const Test1 = () => {
const d = new Date()
return (
<div className={`${utilStyles.redContainer}`}>
<h1>It's {d.toISOString()} and I'm Test1 component. My background should be red</h1>
</div>
)
}
和测试2:
export const Test2 = () => {
const d = new Date()
return (
<div className={`${utilStyles.blueContainer}`}>
<h1>It's {d.toISOString()} and I'm Test2 component. My background should be blue</h1>
</div>
)
}
还有这个 CSS:
.redContainer {
background-color: red;
}
.blueContainer {
background-color: blue;
}
在通过编译代码构建和提供代码执行代码时,背景颜色被缓存。当使用yarn dev 运行时,它工作得很好。
这是意想不到的结果:
Screenshot with Test1 component being rendered with blue background
PS:我使用getInitialProps 来防止 Next.js 缓存该页面中的任何内容,但对于我的实际用例,该选项无效,因为我需要计算渲染条件在客户端,因为它将取决于浏览器的本地日期。
【问题讨论】:
标签: css typescript caching next.js