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

React.js使用map()遍历列表时出现唯一key属性警告求助

React列表子项缺少唯一key警告问题解答

问题描述

我在Chrome调试控制台收到如下警告:

react-jsx-dev-runtime.development.js:87 Warning: Each child in a list should have a unique "key" prop.

Check the render method of App. See https://reactjs.org/link/warning-keys for more information. at div at App (http://localhost:3000/static/js/bundle.js:31:80)

我的代码功能正常,但不清楚这个警告的原因,想知道这是不是真实问题、能不能忽略,寻求帮助。我曾搜索该警告信息但未找到有用内容。

附上我的代码:

import './App.css';
import {ethers} from "ethers";
import { useState } from 'react';
 

function App() {
  const [account, setAccount] = useState("")
  const [data, setData] = useState([])
  
  console.log(data);

  const connect = async () => {
    const provider = new ethers.providers.Web3Provider(window.ethereum)
    let res = await provider.send("eth_requestAccounts", []);
    setAccount(res[0]);
    getData(res[0]);
  }
  const getData = (_account) => {
    const options = {method: 'GET', headers: {accept: 'application/json'}};
  
    fetch(
      'https://api.opensea.io/api/v1/collections?asset_owner=0x3FB65FEEAB83bf60B0D1FfBC4217d2D97a35C8D4&offset=0&limit=3',
      // `https://api.opensea.io/api/v1/collections?asset_owner=${_account}&offset=0&limit=3`,
       options)
      .then(response => response.json())
      .then(response => {
        setData(response);
        console.log(response)})
      .catch(err => console.error(err));
  };
  return (
    <div className="App">
      <button
        onClick={connect}>
          Connect
      </button>
      {data.map(nft => {
        return(<div>
          <img src={nft.featured_image_url} width="100px" height="100px"/>
          <p>
            {nft.discord_url}
          </p>
          <p>
            {nft.banner_image_url}
          </p>
        </div>)
      })}
      <button
        onClick={getData}>
          GetData
      </button>
      
    </div>
  );
}

export default App;

问题原因

这个警告是React的核心机制要求:当你用map渲染列表时,每个子元素必须有唯一的key属性。React依赖这个key来识别列表中每个元素的身份,在列表更新(比如排序、增删元素)时高效地重新渲染,避免不必要的DOM操作。

这是真实问题吗?能不能忽略?

  • 功能正常时看似不影响,但这不是可以忽略的问题。如果后续列表有更新操作(比如新增、删除、排序NFT),没有key会导致React无法正确追踪元素,可能出现渲染错误、状态混乱,甚至性能下降。
  • 开发环境下的警告就是在提示你修复这个潜在问题,生产环境虽然不会显示警告,但潜在的渲染问题依然存在。

修复方法

从OpenSea API返回的数据来看,每个NFT集合都有唯一的slug字段(也可以用contract_address),把它作为key绑定到map渲染的最外层div上即可:

修改后的map部分代码:

{data.map(nft => {
  return(<div key={nft.slug}> {/* 添加唯一key */}
    <img src={nft.featured_image_url} width="100px" height="100px"/>
    <p>
      {nft.discord_url}
    </p>
    <p>
      {nft.banner_image_url}
    </p>
  </div>)
})}

注意:不要用数组索引index作为key,除非列表是静态的、永远不会排序或增删元素。因为索引会随着列表变化而改变,依然会导致React的渲染追踪出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:25:18