这是我的路由文件夹结构:
我想实现一个像这样的URL结构:http://localhost:3000/brands/toyota/toyota-innova
在[brandSlug]/index.js
上,我使用getStaticPaths
来定义路径,它似乎工作正常。当我输入toyota
和mitsubishi
以外的参数时,它会显示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-innova
或toyota/random-parameter123
。
如何使用getStaticPaths和嵌套的动态路由正确地做到这一点?
1条答案
按热度按时间tyky79it1#
您还没有提供品牌Slug在您的车辆Slug获取静态 prop 。
它应该是: