无法在使用 react 构建的简单博客中添加新文章



我用 React 构建了一个简单的博客。每当我尝试添加新文章时,我都遇到了问题。我收到以下错误。 类型错误:无法读取 null 的属性"赞成票">

文章页面代码如下:

const ArticlePage = ({ match }) => {
const name = match.params.name;
const article = ArticleContent.find(article => article.name === name);
const [articleInfo, setArticleInfo] = useState({ upvotes: -1, comments: [] });
useEffect(() => {
const fetchData = async () => {
const result = await fetch(`/api/articles/${name}`);
const body = await result.json();
setArticleInfo(body);
}
fetchData();
}, [name]);
if (!article) return <notFoundPage />
const otherArticles = ArticleContent.filter(article => article.name !== name);
return (
<>
<h1>{article.title}</h1>
<UpvotesSection articleName={name} upvotes={articleInfo.upvotes} setArticleInfo={setArticleInfo} />
{article.content.map((paragraph, key) => (
<p key={key}>{paragraph}</p>
))}
<CommentsList comments={articleInfo.comments} />
<AddCommentForm articleName={name} setArticleInfo={setArticleInfo} />
<h3>Other Articles:</h3>
<ArticlesList articles={otherArticles} />
</>
);
}

这就是错误告诉我要看的地方。我试图将赞成部分注释掉,它只是将错误更改为评论。我将它们都注释掉,文章呈现,但它没有评论或赞成票。

您收到错误是因为您的articleInfonull。 这就是为什么它在您的return方法中找不到upvotescomments的原因。

您的初始状态包含一个对象{ upvotes: -1, comments: [] }。所以这不是问题所在。唯一可能出错的地方是您打电话给setArticleInfo的地方。

您是否尝试过记录body变量? 我的猜测是你的body变量是null,通过调用setArticleInfo(body),你将articleInfo设置为null因此它抛出错误。

最新更新