已添加key仍触发React列表子元素唯一key prop警告求助
问题原因及解决方案
核心问题
你遇到的key警告,本质是你使用的article.id并不存在,同时存在多余的无效key设置:
- NewsAPI的
top-headlines接口返回的文章对象里没有id字段,article.id实际是undefined,相当于所有循环元素的key都重复,触发React警告。 - 你给
<a>标签内部的<img>、<h1>、<p>都添加了key,这完全没必要——key只需要设置在map循环返回的最外层元素上,内部子元素不需要key。 index.tsx中给<NewsFeed>设置的key={news.article}是无效的:news.article字段不存在(正确字段是news.articles),且<NewsFeed>并非在列表循环中渲染,不需要设置key。
修复步骤
1. 使用有效唯一字段作为key
因为新闻的url是唯一的,直接用article.url替代article.id作为key:
2. 移除不必要的key
删除<a>内部子元素的key,只保留循环最外层元素的key;同时删除index.tsx中<NewsFeed>的无效key。
修改后的代码示例
NewsFeed.tsx
import React, { useState } from 'react' import Feeds from './Feeds' export default function NewsFeed({ news }: any) { const [date, setDate] = useState(new Date()) return ( <div className='bg-white'> <div className='flex justify-between p-4'> <h1>Welcome to clone BBC.com</h1> <h1>{date.toDateString()}</h1> </div> {news.articles.slice(0, 1).map((article: any) => ( <a key={article.url} href={article.url} className="relative"> <img className='w-full' src={article.urlToImage ? article.urlToImage : "./ALT.jpg"} alt="" /> <h1 className='text-white absolute bottom-[40%] left-[5%] lg:text-2xl text-xl'>{article.title}</h1> <p className='text-white absolute bottom-[30%] left-[5%] line-clamp-1'>{article.description}</p> </a> ))} <div className='grid grid-flow-row-dense md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'> {news.articles.slice(1).map((article: any) => ( <Feeds url={article.url} className="" key={article.url} urlToImage={article.urlToImage} title={article.title} description={article.description} /> ))} </div> </div> ) }
index.tsx
import Head from 'next/head' import Header from '../components/Header'; import NewsFeed from '../components/NewsFeed'; export default function Home({ news }: any) { return ( <div className='bg-gray-100 '> <Head> <title>Create Next App</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head> <Header /> <main className='mx-5 my-5'> <NewsFeed news={news} /> </main> </div> ) } export async function getServerSideProps(context: any) { const news = await fetch("https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=a252437b389346d0b79f7417e0ca9e30") .then(res=>res.json()); return { props: { news, } } }
内容的提问来源于stack exchange,提问作者SOOVIK KUNDU
相关产品推荐
相关产品推荐

