[英]nested array object property return undefined typeError in react redux
i want to show the post detail in frontend.我想在前端显示帖子详细信息。 my api is showing the postdetail like below captured in postman:
我的 api 正在显示 postman 中捕获的 postdetail 如下所示:
"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
}
}
Here, creator is an Object.在这里,creator 是一个对象。 Whereas .map function is for Array.
而 .map 函数用于数组。 To map an Object you can check: map function for objects (instead of arrays)<\/a>
要映射对象,您可以检查:
对象的映射函数(而不是数组)<\/a>
You have provided your object with creater,您已经为您的对象提供了创建者,
"creator": {
"_id": "61cd99efa0b8d616a7a53ce1",
"createdAt": "2021-12-30T11:37:19.041Z",
"updatedAt": "2022-01-06T14:35:48.801Z",
"__v": 0,
"bio": "user bio",
"name": "username"
},
make sure the post object contains the "creator" key, and you don't need map() if the state looks exactly like the API response.确保 post 对象包含“创建者”键,如果状态看起来与 API 响应完全一样,则不需要 map()。 If you could show how the state looks that will reveal more of the issue.
如果您可以展示该州的外观,那将揭示更多问题。
For the first time when the component will mount, the value of the creator will be undefined.当组件第一次挂载时,creator 的值将是未定义的。 You need to add a check before getting the nested value.
您需要在获取嵌套值之前添加检查。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.