next.js getStaticPaths 列出每条路径还是仅列出附近的路径?

Tre*_*est 3 static next.js

使用 Next.js 导出静态页面,我在动态路由中得到它,就像pages/[id].js我在该getStaticPaths部分中放置的任何路径都将被创建。凉爽的。

列出每个页面是否更好:

getStaticPaths(){
  return (
    // some function to spit out a list of every possible page
  )
}
Run Code Online (Sandbox Code Playgroud)

或者

getStaticPaths(){
  return (
    // some function to return the next and previous page
  )
}
Run Code Online (Sandbox Code Playgroud)

或者这有关系吗?

sub*_*tra 9

对于动态路由示例posts/[id].js getStaticPaths需要定义一个路径列表,以便Next.js在构建时预渲染所有指定的路径。

该函数getStaticPaths需要返回一个具有paths属性的对象,该对象是一个包含路由参数和属性的数组,该属性fallback将为 true 或 false。fallback对于未从函数返回的任何路径,如果将其设置为 false,则不会getStaticPaths预渲染,因此会生成404页面。

如果您知道需要提前渲染的所有路径,则可以将其设置fallback为 false。这是一个示例。

 // getStaticPaths for /category/[slug] where slug can only be -
 // either 'category-slug-1', 'category-slug-2' or 'category-slug-3'

 export const getStaticPaths = async () => {

   return {
      paths: [
        { params: { slug: 'category-slug-1'} },
        { params: { slug: 'category-slug-2'} },
        { params: { slug: 'category-slug-3'} }
       ],
     fallback: false // fallback is set to false because we already know the slugs ahead of time
   }   

 }

Run Code Online (Sandbox Code Playgroud)

假设您有一个/posts/[id].js来自数据库的路由和 ID,并且每天都会创建新的帖子。在这种情况下,您可以返回已经存在的路径来预渲染一些页面。并设置fallbacktrue和根据请求,Next.js 将提供页面的后备版本,而不是为404未从函数返回的路径显示页面getStaticPaths,然后在后台,nextjs 将调用getStaticProps请求的路径并将数据作为将用于在浏览器中呈现页面的 JSON。

这是一个例子,


export const getStaticPaths = async () => {
   const posts = await // your database query or fetch to remote API
   
   // generate the paths
   const paths = posts.map(post => ({ 
        params: { id: post.id } // keep in mind if post.id is a number you need to stringify post.id
      })
   );

   return {
      paths,
      fallback: true
   }   

 }

Run Code Online (Sandbox Code Playgroud)

PS - 使用fallbackset to 时,true您需要在组件中呈现某种后备组件,NextPage否则当您尝试从 props 访问数据时,它会抛出类似错误cannot read property ...x of undefined

你可以像这样渲染一个回退,

// in your page component
import {useRouter} from 'next/router';

const router = useRouter();

if (router.isFallback) {
   return <div>loading...</div>
}
Run Code Online (Sandbox Code Playgroud)