在Next JS中导航到动态路由页面返回错误



当从同一web应用程序中的链接导航到动态路由页面时,点击链接的结果是预期的:我导航到产品页面(http://localhost/1)。

但是当我通过在搜索栏中指定产品编号(导航到http://localhost/2)直接导航时,我得到了以下错误:

Server Error
TypeError: Cannot read property 'image' of undefined 
> | <Image src={"/../public/images/" + p.image}
^

到目前为止,我已经尝试使类型匹配并阅读动态路由的Next JS文档。

我已经从过滤器中删除了数组0,但仍然没有分辨率。

是否有可能路由只在Next JS中点击链接时有效?是不是有什么我忽略了的场景?

页面/(pid) . js

import { useRouter } from 'next/router'
import Image from 'next/image'
import data from '../products.json'
export default function Template() {
const router = useRouter()
const { pid } = router.query
const p = data.filter(product => product._id == pid)[0]  // Choose one result
return (
<Image src={"/../public/images/" + p.image}
height="500px"
width="500px" />
)
}

products.json

[
{
"_id": 1,
"name": "Toyota",
"image": "toyota.png"
},
{
"_id": 2,
"name": "BMW",
"image": "bmw.png"
}
]

更新:我试图硬编码图像标签中的src属性,新的错误说其他引用是问题。因此,我可以放心地说,问题在于调用数据对象时没有返回对象。

我解决了这个问题!

使用'useRouter()'函数使用动态路由是不够的。我还必须定义这两个函数:

export async function getStaticProps(context) {
// No-op since getStaticPaths needs getStaticProps to be called.
return { props: {} }
}
export async function getStaticPaths() {
const dynamicFiles = products.map(product => (
{
params: { pid: String(product._id) },  // Product IDs are ints in JSON file
}
))
return {
paths: dynamicFiles,
fallback: false
}
}

这是有意义的,因为您不希望将随机路径用作变量。例如,当1234不是有效选项时,用户可以指定http://localhost/1234

https://nextjs.org/learn/basics/dynamic-routes/implement-getstaticprops

最新更新