【问题标题】:React.js warning when iterating a list with map()使用 map() 迭代列表时出现 React.js 警告
【发布时间】:2022-12-09 16:35:02
【问题描述】:

我从 Web 调试控制台收到此警告:

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;

该代码实际上按我的预期工作。但是当从 chrome 打开调试控制台时,我可以看到上面粘贴的这个警告。

不确定为什么会出现此警告?需要一些帮助,谢谢

用谷歌搜索此警告消息,但找不到有关此警告的有用信息。 这个警告是一个真正的问题还是可以忽略?

【问题讨论】:

标签: reactjs


【解决方案1】:

当你用 react 映射时,你必须提供一个唯一的键。

方法如下:

 {data.map((nft, index) => {
        return(<div key={index}>

这只是一个例子。您可以提供自己的索引。div key={nft} 如果每个数据都是唯一的,那么它也可以工作。

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多