我用 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} />
</>
);
}
这就是错误告诉我要看的地方。我试图将赞成部分注释掉,它只是将错误更改为评论。我将它们都注释掉,文章呈现,但它没有评论或赞成票。
您收到错误是因为您的articleInfo
null
。 这就是为什么它在您的return
方法中找不到upvotes
或comments
的原因。
您的初始状态包含一个对象{ upvotes: -1, comments: [] }
。所以这不是问题所在。唯一可能出错的地方是您打电话给setArticleInfo
的地方。
您是否尝试过记录body
变量? 我的猜测是你的body
变量是null
,通过调用setArticleInfo(body)
,你将articleInfo
设置为null
因此它抛出错误。