如何在Next JS中对动态嵌套路由使用getStaticPaths?

bakd9h0s  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(127)

这是我的路由文件夹结构:

我想实现一个像这样的URL结构:http://localhost:3000/brands/toyota/toyota-innova
[brandSlug]/index.js上,我使用getStaticPaths来定义路径,它似乎工作正常。当我输入toyotamitsubishi以外的参数时,它会显示404页面,这是所需的行为。

import { useRouter } from 'next/router'

export async function getStaticPaths() {
    return {
        paths: [{ params: { brandSlug: 'toyota' } }, { params: { brandSlug: 'mitsubishi' } }],
        fallback: false,
    };
}

export async function getStaticProps() {

    const response = await fetch('http://localhost:3001/brands');
    const brands = await response.json();

    return {
        props: {
            brands: brands,
        }
    };
}

const Brand = ({ brands }) => {

    const router = useRouter()
    console.log(brands)

    return (
        <div>
            <p>Showing all vehicles of {router.query.brandSlug}</p>
        </div>
    )
}

export default Brand

然而,在[brandSlug]/[vehicleSlug].js上,使用下面的代码,当我输入时返回一个错误:
http://localhost:3000/brands/toyota/toyota-innova

import { useRouter } from 'next/router'

export async function getStaticPaths() {
    return {
        paths: [{ params: { vehicleSlug: 'toyota-innova' } }, { params: { vehicleSlug: 'toyota-corolla' } }],
        fallback: false,
    };
}

export async function getStaticProps() {

    // const response = await fetch('api here');
    // const vehicle = await response.json();

    // gonna fetch vehicle details here, made empty for now

    return {
        props: {
            vehicle: [],
        }
    };
}

const VehicleDetails = () => {

    const router = useRouter()

    return (
        <p>Showing Vehicle details of {`${router.query.vehicleSlug}`}</p>
    )
}

export default VehicleDetails

这就是错误:

Error: A required parameter (brandSlug) was not provided as a string received undefined in getStaticPaths for /brands/[brandSlug]/[vehicleSlug]
它说缺少brandSlug,但我已经提供了它
我的nested dynamic route结构可以使用getStaticPaths吗?
我所期望的是能够输入url http://localhost:3000/brands/toyota/toyota-innova并抛出404页面,例如使用mitsubishi/toyota-innovatoyota/random-parameter123
如何使用getStaticPaths和嵌套的动态路由正确地做到这一点?

tyky79it

tyky79it1#

您还没有提供品牌Slug在您的车辆Slug获取静态 prop 。
它应该是:

export async function getStaticPaths() {
    return {
        paths: [{ 
            params: { 
               brandSlug: 'toyota',
               vehicleSlug: 'toyota-innova',
            }
        }],
        fallback: false,
    };
}

相关问题