You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React新闻应用控制台报相同key子元素警告如何消除?

React新闻应用key重复警告解决方案

你遇到的Warning: Encountered two children with the same key警告核心原因是列表渲染时使用的key值出现了重复,结合你的代码有以下几个具体诱因:

  • 你当前使用element.url作为唯一key,但NewsAPI返回的部分文章可能存在url重复的情况,极少数场景下还会出现url为空的问题
  • 无限加载的fetchMoreData方法存在状态异步更新问题:setPage是异步操作,你调用setPage(page+1)后立即使用page参数发起请求,实际请求的还是当前页的内容,导致旧页数据重复拼接到articles数组中,自然出现重复key
  • 额外小问题:loading状态初始值错误声明为数组[true],应该为布尔值true

修复步骤

步骤1:修复fetchMoreData的异步请求问题

不要依赖更新前的page值发起请求,直接提前计算好下一页页码作为请求参数,同时使用状态更新的函数式写法避免闭包问题:

const fetchMoreData = async () => {
  const nextPage = page + 1
  let url = `https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apiKey=${props.apiKey}&page=${nextPage}&pageSize=${props.pageSize}`;
  let data = await fetch(url);
  let parsedData = await data.json();
  // 用函数式更新获取最新的articles状态,避免闭包问题
  setArticles(prevArticles => prevArticles.concat(parsedData.articles))
  setTotalResults(parsedData.totalResults)
  setPage(nextPage)
  setLoading(false)
};

步骤2:替换更可靠的key值

不要只用element.url,可以组合文章发布时间、url、索引三个维度生成唯一key,彻底避免重复:

{articles.map((element, index) => {
  return <div className="col-md-4" key={`${element.publishedAt}-${element.url}-${index}`}>
    <NewsItem title={element.title ? element.title: ""} description={element.description ? element.description: ""} imageUrl={element.urlToImage} newsUrl={element.url} author={element.author} date={element.publishedAt} source={element.source.name} bCol={"bg-danger"}
    />
  </div>
})}

步骤3:修复loading状态的初始值错误

// 把原来的数组格式改为布尔值
const [loading, setLoading] = useState(true)

可选优化:新增数据去重逻辑

如果API仍偶发返回重复文章,可以在拼接新数据前做一次去重,从根源避免重复数据进入列表:

setArticles(prevArticles => {
  const newArticles = parsedData.articles.filter(newArt => !prevArticles.some(oldArt => oldArt.url === newArt.url))
  return prevArticles.concat(newArticles)
})

内容的提问来源于stack exchange,提问作者Sanjeeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 08:09:01