如何解决使用getStaticPaths在localhost上的NextJS和json-server加载缓慢
我正在建立一个小型的电子商务网站,并设置了我的索引页面以生成静态道具以及我的个人产品页面,因为我们还没有很多产品。我遇到的问题是每次用户单击时加载速度都很慢,好像我错过了有关NextJS数据获取工作方式的关键问题。 因此,以下是摘要,有关完整项目,请访问:https://github.com/danieltosaba/framer-motion
索引页
export default function Home({ blankets }: HomeProps) {
const classes = useStyles();
return (
<motion.div exit={{ opacity: 0 }} initial={{opacity: 0}} animate={{opacity: 1}}>
<div>
<Head>
<title>Framer Motion Transitions</title>
</Head>
<main>
<Grid container spacing={2}>
<Grid item xs={12}>
<h1>CHOOSE YOUR BLANKET</h1>
</Grid>
{blankets.map((blanket) => (
<Grid key={blanket.id} item xs={12} sm={6} lg={4}>
<Card>
<Link href="/product/[id]" as={`/product/${blanket.id}`}>
<a>
<img
src={blanket.imageUrl.cover}
alt={blanket.name}
className={classes.image}
/>
</a>
</Link>
</Card>
</Grid>
))}
</Grid>
</main>
</div>
</motion.div>
);
}
export const getStaticProps: GetStaticProps = async (ctx) => {
const response = await fetch(
"http://localhost:4001/blankets/"
);
const blankets = await response.json();
return {
props: { blankets },};
};
产品页面
type ProductDetailsProps = Blanket;
export default function ProductDetails({ name,description,imageUrl,size,price }: ProductDetailsProps) {
let images = [];
imageUrl.url.forEach((img) => {
images.push({
original: img,thumbnail: img,});
});
return (
<motion.div
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Imagegallery items={images} />
</Grid>
<Grid item xs={12} sm={6}>
<Paper elevation={0}>
<Card>
<CardContent>
<Typography variant="h4" gutterBottom>
{name}
</Typography>
<Typography variant="subtitle1">
Price: {price.small}
</Typography>
<Typography variant="body1" gutterBottom>
{description}
</Typography>
</CardContent>
</Card>
</Paper>
</Grid>
</Grid>
</motion.div>
);
}
export const getStaticProps: GetStaticProps = async (context) => {
const id = context.params.id;
const response = await fetch(
`http://localhost:4001/blankets/${id}`
);
const blanket = await response.json();
return {
props: blanket,};
};
export const getStaticPaths: GetStaticPaths = async () => {
const response = await fetch(
"http://localhost:4001/blankets/"
);
const blankets: Blanket[] = await response.json();
const paths = blankets.map((blanket) => {
return { params: { id: blanket.id.toString() } };
});
return {
paths,fallback: false,};
};
任何帮助都受到欢迎!
解决方法
仔细阅读文档后,我发现
,在开发中(下一个开发人员),getStaticPaths将在每个 请求。
每次在开发中请求页面时都会调用 getStaticPaths。因此,如果您有 500 个产品,并且在 getStaticPaths 中获取所有产品,则意味着在每次加载页面时,您将遍历所有项目,并为每个项目创建路径。届时将调用 getStaticProps 并呈现您的页面。
在生产中它会有所不同,因为它只会在“构建时间”构建,然后根据用户的请求重新生成页面,具体取决于您为“重新验证”选项设置的时间间隔。
但我能给出的最好建议只是限制您在开发时在 getStaticPaths 中请求的数据数量。希望我们能尽快在开发中获得更好的体验
如果我说错了,请纠正我!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。