【问题标题】:Next.js Static Nested Dynamic Routing with nested iterationNext.js 具有嵌套迭代的静态嵌套动态路由
【发布时间】:2021-12-02 03:02:25
【问题描述】:

假设您有来自关系数据库的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 }
}

【问题讨论】:

  • 您是否从 supbase 的请求中获得了预期的数据?如果 categories 为空,则可以解释为什么您会得到一个空的 paths 数组。
  • 当然,我的数据在 supabase 上
  • 如果您将count 记录到控制台,它是否会在每次forEach 迭代时返回预期值?
  • @juliomalves 是的,计数存在
  • 知道了,应该使用 for/of 而不是 forEach

标签: javascript routes next.js url-routing supabase


【解决方案1】:

异步调用不适用于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 }
}

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 2023-03-09
    • 1970-01-01
    • 2021-09-28
    • 2021-03-14
    • 2022-07-29
    • 2021-01-20
    • 1970-01-01
    • 2016-04-06
    相关资源
    最近更新 更多