嵌套数组对象属性在 React Redux 中返回未定义的类型错误
2022-02-06
773
我想在前端显示帖子详情。我的 api 显示的帖子详情如下,在 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>
);
}
有三个错误:
- 未捕获的类型错误:创建者未定义
- 组件中发生上述错误:
- 未捕获的类型错误:创建者未定义
如果我将
我该如何解决? 提前谢谢您
3个回答
组件首次挂载时,创建者的值将未定义。您需要在获取嵌套值之前添加检查。
<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>
注意:还有一点,Creator 不是数组。它是一个对象。因此您无法映射对象。如果它是数组,您也必须在这种情况下进行上述检查。
xdeepakv
2022-02-06
此处,creator 是一个对象。而 .map 函数用于数组。 要映射对象,您可以检查: 用于对象(而不是数组)的 map 函数
Avni Agrawal
2022-02-06
您已为对象提供了创建者,
"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>
Ajay Raja
2022-02-06