嵌套数组对象属性返回未定义的typereact redux中的错误



我想在前端显示帖子的详细信息。我的api显示了postloader:中捕获的如下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
}
}

我想在前端展示这篇文章的细节,这是代码:

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>
);
}

有三个错误:

  1. 未捕获类型错误:创建者未定义
  2. 组件中出现上述错误:
  3. 未捕获的类型错误:创建者未定义

如果我将静音

  • 由{creator.map((m,i(=>创建({m.name}))}
  • 然后它显示了没有帖子作者姓名的帖子细节。但是我想显示作者的名字。我该怎么解决?提前感谢

    当组件第一次装入时,创建者的值将未定义。在获取嵌套值之前,您需要添加一个检查。

    <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不是数组。它是一个对象。所以你无法映射对象。如果它是一个数组,那么在这种情况下也必须进行上述检查

    这里,creator是一个Object。而.map函数用于Array。要映射对象,可以检查:对象的映射函数(而不是数组(

    您已经为您的对象提供了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"
    },
    

    map方法仅适用于Array。但是这里你已经使用对象

    <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>
    

    确保post对象包含"创建者";键,并且如果状态看起来与API响应完全一样,则不需要map((。如果你能展示这个州的样子,就会揭示更多的问题。

    相关内容

    • 没有找到相关文章

    最新更新