任何人都可以帮助我处理这些动态内容(nextJ)
我有一个包括Web内容的对象:
const postContent = {
post1: {
title: 'Post 1',
content: 'Content 1'
},
post2: {
title: 'Post 2',
content: 'Content 2'
}
}
和一个动态[post] .js:
import { postContent } from "../../lib";
import { useRouter } from "next/router";
const postWeb = () => {
const router = useRouter();
const { post } = router.query;
const postGet = postContent[post]
console.log(postGet)
return (
<div>
{postGet.title}
</div>
);
}
export default postWeb;
我使用[post]从postcontent等postcontcontent.post1(依赖 /post /post /post /post1或 /post /post /post2)获取对象。 我使用console.log(Postget)并接收一个对象: {title:'post 1',content:'content 1'}
。但是,当我使用postget.title时,它将是未定义的并收到错误:
TypeError: Cannot read properties of undefined (reading 'title')
This error happened while generating the page. Any console logs will be displayed in the terminal window
我不知道如何解决此问题,我发现如何在NextJ中使用Dynamic Route。谁能帮助我解决这些问题,或者可以给我一些有关这些的教程?
谢谢。
I have an object including web content:
const postContent = {
post1: {
title: 'Post 1',
content: 'Content 1'
},
post2: {
title: 'Post 2',
content: 'Content 2'
}
}
And a dynamic [post].js:
import { postContent } from "../../lib";
import { useRouter } from "next/router";
const postWeb = () => {
const router = useRouter();
const { post } = router.query;
const postGet = postContent[post]
console.log(postGet)
return (
<div>
{postGet.title}
</div>
);
}
export default postWeb;
I use [post] to get the object from postContent like postContent.post1 (depend on URL like /post/post1 or /post/post2)
I use console.log(postGet) and receive an object:{title: 'Post 1', content: 'Content 1'}
. But when I use postGet.title, it will be undefined and receive an error:
TypeError: Cannot read properties of undefined (reading 'title')
This error happened while generating the page. Any console logs will be displayed in the terminal window
I don't know how to fix this, I'm figured out how to use dynamic route with content in Nextjs. Can anyone help me with these or can give me tutorials about these?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最初渲染中的问题
,您正在访问最初不存在的对象的属性。
解决方案
考虑添加默认值或短路
Problem
In your initial rendering, you are accessing a property of an object that is initially doesn't exist.
Solution
Consider adding default value or short circuiting