gpt4 book ai didi

javascript - 为什么我们使用getStaticProps时只需要getStaticPaths()?

转载 作者:行者123 更新时间:2023-12-05 05:39:09 24 4
gpt4 key购买 nike

如果我们有动态路由

[id].js

function id() {
return <h1>Hello World</h1>
}
export default id

然后我们使用 npm run build 构建静态页面,结果是 [id].html 页面。任何带有/something 的路由都可以工作并显示 Hello World

但是如果我们通过getStaticProps()的返回值动态生成页面的内容在组件中:

function id(props) {
const { test } = props
return <h1>{test.foo}</h1>
}
export default id

然后我们需要再次使用 getStaticPaths() 来指定可能的路径。

为什么我们使用getStaticProps时只需要getStaticPaths()?

最佳答案

nextjs docs简单地说:

If a page has Dynamic Routes and uses getStaticProps, it needs to define a list of paths to be statically generated.

动态 SSG 页面需要 getStaticPaths,因为 Vercel 决定这样做。


如果您想在使用 getStaticProps 的同时保持不需要来自 getStaticPaths 的预定义路由的行为,您可以使用 fallback: true告诉 nextjs 渲染路由,即使它们不是由 getStaticPaths 预定义的。

你可以发送一个空的paths数组并设置fallback: true:

export async function getStaticPaths() {
const paths = [];
return { paths, fallback: true };
}

这将导致所有路由仍然可以访问,就像问题第一部分中的行为一样。这是 codesandbox 上的完整示例。在示例中,尝试转到 /test/any-route-you-want 并注意路线仍将呈现:Edit blissful-dan-40qkvq

关于javascript - 为什么我们使用getStaticProps时只需要getStaticPaths()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72765738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com