无法在使用react构建的简单博客中添加新文章
我已经用React建立了一个简单的博客。每当我尝试添加新文章时,我都会遇到问题。我收到以下错误。TypeError:无法读取null的属性'upvotes'
文章页面代码如下:
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={articleInfoments} />
<AddCommentForm articleName={name} setArticleInfo={setArticleInfo} />
<h3>Other Articles:</h3>
<ArticlesList articles={otherArticles} />
</>
);
}
这就是错误告诉我的地方。我试图将upvotes部分注释掉,它只是将错误更改为注释。我将它们都注释掉了,并且文章呈现了,但是没有评论或赞誉。
回答如下:您收到错误,因为您的articleInfo
为null
。这就是为什么在您的upvotes
方法中找不到comments
或return
的原因。
您的初始状态包含对象{ upvotes: -1, comments: [] }
。所以那不是问题。唯一可能出错的地方是您呼叫setArticleInfo
的地方。
您是否尝试记录您的body
变量?我的猜测是,您的body
变量为null
,并通过调用setArticleInfo(body)
将您的articleInfo
设置为null
,因此为什么会引发错误。
无法在使用react构建的简单博客中添加新文章
我已经用React建立了一个简单的博客。每当我尝试添加新文章时,我都会遇到问题。我收到以下错误。TypeError:无法读取null的属性'upvotes'
文章页面代码如下:
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={articleInfoments} />
<AddCommentForm articleName={name} setArticleInfo={setArticleInfo} />
<h3>Other Articles:</h3>
<ArticlesList articles={otherArticles} />
</>
);
}
这就是错误告诉我的地方。我试图将upvotes部分注释掉,它只是将错误更改为注释。我将它们都注释掉了,并且文章呈现了,但是没有评论或赞誉。
回答如下:您收到错误,因为您的articleInfo
为null
。这就是为什么在您的upvotes
方法中找不到comments
或return
的原因。
您的初始状态包含对象{ upvotes: -1, comments: [] }
。所以那不是问题。唯一可能出错的地方是您呼叫setArticleInfo
的地方。
您是否尝试记录您的body
变量?我的猜测是,您的body
变量为null
,并通过调用setArticleInfo(body)
将您的articleInfo
设置为null
,因此为什么会引发错误。