我想在前面展示这篇文章的细节。我的api显示了下面在postman中捕获的postman详细信息:
"message": "Posts fetched successfully!",
"posts": {
"_id": "61f05f676793d49f466e7aaa",
"title": "Liberal Arts Student Sample",
"content": "The three-page.",
"creator": {
"_id": "61cd99efa0b8d616a7a53ce1",
"createdAt": "2021-12-30T11:37:19.041Z",
"updatedAt": "2022-01-06T14:35:48.801Z",
"__v": 0,
"bio": "user bio",
"name": "username"
},
"Comments": [],
"created": "2022-01-25T20:36:55.095Z",
"createdAt": "2022-01-25T20:36:55.096Z",
"updatedAt": "2022-01-25T20:36:55.096Z",
"__v": 0
}
}我想在前面展示这个帖子的细节,下面是代码:
export default function PostDetail() {
const { postId } = useParams();
const post = useSelector((state) => state.post)
const dispatch = useDispatch();
const { title, content,creator, created } = post;
const fetchPostDetail = async (id) => {
const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
.catch(err => {
console.log(err);
})
dispatch(selectedPost(response.data.posts));
}
useEffect(() => {
fetchPostDetail(postId)
}, [])
return (
<div>
<h1>Post Detail</h1>
<div>
<h2>{title}</h2>
<i>posted in {created}</i>
<li>Created by {creator.map((m,i)=>(
<b key={i}>{m.name}</b>
))}</li>
<p>{content}</p>
</div>
</div>
);
}有三个错误:
component:
中。
如果我静音
创建
然后显示没有post作者名称的post细节。但我想告诉作者的名字。
我该怎么解决呢?先谢谢你
发布于 2022-02-06 14:40:05
当组件首次挂载时,创建者的值将是未定义的。在获得嵌套值之前,您需要添加一个检查。
<div>
<h1>Post Detail </h1>
<div>
<h2>{title} </h2>
<i> posted in {created} </i>
{creator && <li> Created by :{creator.name}</li>}
<p> {content} </p>
</div>
</div>注:还有一件事,创建者不是数组。它是一个物体。所以你不能绘制物体的地图。如果它是一个数组,在这种情况下也必须进行上面的检查。
发布于 2022-02-06 13:42:15
在这里,创建者是一个对象。而.map函数是用于数组的。要映射对象,可以检查:map function for objects (instead of arrays)
发布于 2022-02-06 13:43:50
你为你的对象提供了造物主,
"creator": {
"_id": "61cd99efa0b8d616a7a53ce1",
"createdAt": "2021-12-30T11:37:19.041Z",
"updatedAt": "2022-01-06T14:35:48.801Z",
"__v": 0,
"bio": "user bio",
"name": "username"
},map方法只适用于数组。但是在这里你用了宾语
<div>
<h1>Post Detail</h1>
<div>
<h2>{title}</h2>
<i>posted in {created}</i>
<li>Created by {creator.map((m,i)=>(
<b key={i}>{m.name}</b>
))}
</li>
<p>{content}</p>
</div>
</div>您可以将代码替换为
<div>
<h1>Post Detail</h1>
<div>
<h2>{title}</h2>
<i>posted in {created}</i>
<li><b>Created by {creator.name}</b></li>
<p>{content}</p>
</div>
</div>https://stackoverflow.com/questions/71007652
复制相似问题