繁体   English   中英

Next.js 静态嵌套动态路由与嵌套迭代

[英]Next.js Static Nested Dynamic Routing with nested iteration

假设您有来自关系数据库的postscategories数据:

// category_id on categories.id
const posts = [
  { id: '1', title: 'dream pc', category_id: '1' },
  { id: '2', title: 'my dream house design', category_id: '1' },
  { id: '3', title: 'bing chillin', category_id: '2' },
]

const categories = [
  { id: '1', name: 'wishlist' }, 
  { id: '2', name: 'favorites' }
]

这是我的路线格式: /categories/[category]/[page]

目录结构为pages/categories/[category]/[page].js

所以它会产生这些路径:

  • /categories/wishlist/1
  • /categories/wishlist/2
  • /categories/favorites/1

我试过这个,但paths返回一个空数组:

// pages/categories/[category]/[page].js

export async function getStaticPaths() {
    const paths = []

    // I'm using supabase
    const { data: categories, error } = await supabase.from('categories').select('id, name')

    categories.forEach(async (c) => {
        const { data, error, count } = await supabase
            .from('posts')
            .select('id', { count: 'exact', head: true })
            .eq('category_id', c.id)

        for (let i = 0; i < count; i++) {
            // This should push the path params to the paths variable, but it didn't
            paths.push({
                params: {
                    // For simplicity, 1 post per page
                    page: i + 1,
                    categoryId: c.id,
                    category: c.name
                }
            })
        }
    })

    // It returns an empty array []
    console.log(paths)

    return { paths, fallback: false }
}

异步调用不适用于Array.forEach ,而是我for (category of categories)

工作代码:

// pages/categories/[category]/[page].js

export async function getStaticPaths() {
    const paths = []

    // I'm using supabase
    const { data: categories, error } = await supabase.from('categories').select('id, name')

    // Use for/of instead of forEach
    for (category of categories) {
        const { data, error, count } = await supabase
            .from('posts')
            .select('id', { count: 'exact', head: true })
            .eq('category_id', c.id)

        for (let i = 0; i < count; i++) {
            paths.push({
                params: {
                    page: (i + 1).toString(),
                    categoryId: category.id,
                    category: category.name
                }
            })
        }
    })

    return { paths, fallback: false }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM