【发布时间】:2020-10-19 08:03:04
【问题描述】:
我正在开发一个迷你 React 应用程序并遇到了问题。为您提供一些背景知识,我使用jsonplaceholder.typicode/com/posts 获取一些帖子并将其显示在主页上。
当我点击单个帖子时,我的想法是它应该将我带到不同的页面并显示所点击帖子的标题和正文。当我单击帖子时,我能够从帖子数组中获取相应的单个帖子(postFound)。顺便说一句,我正在使用 Context API 进行状态管理。并且 console.log(postFound) 返回具有 title 和 body 属性的 post 对象。
但是当我试图访问我的 JSX 中 postFound 对象的 title 属性时,它会抛出一个错误:"TypeError: Cannot read property 'title' of undefined in React"。问题出在哪里?
import React, { useContext } from "react";
import { useParams } from "react-router-dom";
import { postsContext } from "../../Context";
const SinglePostPage = () => {
const { id } = useParams();
const postIdNum = parseInt(id);
const { posts } = useContext(postsContext);
const postFound = posts.find((post) => post.id === postIdNum);
return (
<div>
<h1>{postFound.title}</h1>
</div>
);
};
export default SinglePostPage;
【问题讨论】:
-
错误发生在找到帖子之前,您应该检查是否有帖子。
{postFound && <div><h1>{postFound.title}</h1></div> -
Array.prototype.find 如果没有找到项目,则返回 undefined。在这种情况下,您会发现错误。
-
@merko 谢谢。解决了。 http请求需要时间。所以,我必须有条件地渲染 postFound。
标签: reactjs