ReactJS开发新闻网站时获取文章标题出现多类报错求助
React新闻网站开发问题修复
问题清单
- 警告1: Each child in a list should have a unique "key" prop.
- 警告2: Invalid value for prop
hrefon tag. - 错误3: Uncaught Error: Objects are not valid as a React child (found: object with keys {rendered}).
补充:不渲染标题时页面可显示链接,但仍有前两个警告;渲染标题时页面完全无法加载。
相关代码
LatestArticles.js
import React, { useState, useEffect } from "react"; import Article from "./Article"; function LatestArticles() { const [posts, setPosts] = useState(React.useState("waiting...")); function ArticleGrabber() { useEffect(() => { fetch("URL") .then((response) => response.json()) .then((data) => { setPosts(data); console.log(data); }) .catch((error) => console.log("Authorization failed: " + error.message) ); }, []); } ArticleGrabber(); return ( <div> <h3>Latest Articles</h3> {posts.map((post, index) => ( <ul> <Article key={index} post={post} /> </ul> ))} </div> ); } export default LatestArticles;
Article.js
import React from "react"; import "../Article.css"; function Article(post) { return ( <div className="theArticle"> <h3>{post.post.title.rendered}</h3> <a href={post.post.link}>Article content</a> </div> ); } export default Article;
逐个问题修复
1. 列表子项key警告
- 问题根源:循环生成的
<ul>未设置唯一key,且用index当key稳定性差;嵌套函数内调用useEffect违反Hooks规则,导致状态逻辑异常。 - 修复:
- 把
useEffect移到组件顶层,删除ArticleGrabber函数(Hooks只能在组件/自定义Hook顶层调用); - 将key绑定到
<ul>上,用接口返回的文章唯一ID(如post.id)替代index; - 初始化posts为空数组,避免初始状态类型错误。
- 把
2. <a>标签href无效警告
- 问题根源:初始状态posts设置错误(嵌套useState导致posts为非预期数组),且未校验
post.link就直接渲染,可能出现非字符串值。 - 修复:
- 初始化posts为
[],新增加载状态提示; - 渲染
<a>前校验post.link是否为有效字符串。
- 初始化posts为
3. 对象无法作为React子元素错误
- 问题根源:数据未加载完成就访问
post.title.rendered,或参数未解构导致post.post写法冗余易出错,引发属性访问异常。 - 修复:
- 组件参数用解构语法,直接获取
post; - 加条件渲染,确保
post.title?.rendered和post.link存在后再渲染。
- 组件参数用解构语法,直接获取
修复后代码
LatestArticles.js
import React, { useState, useEffect } from "react"; import Article from "./Article"; function LatestArticles() { const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetch("URL") .then((response) => response.json()) .then((data) => { setPosts(data); setLoading(false); }) .catch((error) => { console.log("Authorization failed: " + error.message); setLoading(false); }); }, []); if (loading) { return <div>Loading...</div>; } return ( <div> <h3>Latest Articles</h3> {posts.map((post) => ( <ul key={post.id}> <Article post={post} /> </ul> ))} </div> ); } export default LatestArticles;
Article.js
import React from "react"; import "../Article.css"; function Article({ post }) { if (!post?.title?.rendered || !post?.link) { return null; } return ( <div className="theArticle"> <h3>{post.title.rendered}</h3> <a href={post.link} target="_blank" rel="noopener noreferrer"> Article content </a> </div> ); } export default Article;
内容的提问来源于stack exchange,提问作者kerrigan
相关产品推荐
相关产品推荐

