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

React中如何遍历对象?新手技术咨询

在React中遍历Country对象的几种方法

嘿,这个问题确实是新手入门React时很常见的场景~别担心,咱们一步步来搞定它!你的Country.js里定义的是一个键值对对象,React没法直接遍历对象,所以需要先用JavaScript的对象方法把它转换成可遍历的数组,再用map()来渲染JSX。

下面给你两种最常用的实现方式:

方法1:用Object.keys()获取键名后遍历

Object.keys()会返回对象所有键名组成的数组(比如你的例子里就是['albania', 'austria', 'belgium', ...]),然后我们可以通过键名去取对应的国家数据:

import Country from './Country';

function CountryList() {
  // 提取所有国家的键名数组
  const countryKeys = Object.keys(Country);

  return (
    <div className="country-list">
      {countryKeys.map(key => {
        // 通过键名获取当前国家的详细数据
        const currentCountry = Country[key];
        // 注意:React列表渲染必须加唯一的key属性,这里用countryNo最合适
        return (
          <div key={currentCountry.countryNo} className="country-item">
            <h3>英文名称:{currentCountry.name.en}</h3>
            <p>国家编号:{currentCountry.countryNo}</p>
            <p>德文名称:{currentCountry.name.de}</p>
            <p>波兰文名称:{currentCountry.name.pl}</p>
          </div>
        );
      })}
    </div>
  );
}

export default CountryList;

方法2:用Object.entries()直接获取键值对(更简洁)

Object.entries()会把对象转换成[键名, 对应值]的二维数组,一步到位拿到键和数据,代码会更简洁:

import Country from './Country';

function CountryList() {
  return (
    <div className="country-list">
      {/* 解构出key(比如'albania')和country(对应的数据对象) */}
      {Object.entries(Country).map(([key, country]) => (
        <div key={country.countryNo} className="country-item">
          <h4>键名:{key}</h4>
          <h3>英文名称:{country.name.en}</h3>
          <p>国家编号:{country.countryNo}</p>
          <p>德文名称:{country.name.de}</p>
        </div>
      ))}
    </div>
  );
}

export default CountryList;

小提示:注意key属性的正确性

React要求列表渲染的每一项都要有唯一的key属性,这里用countryNo是最稳妥的(因为它是唯一的编号),尽量不要用数组的索引当key,否则在列表排序、增删时可能会出现渲染bug。

如果需要对国家列表排序或者过滤,也可以先处理数组再渲染,比如按国家编号升序排列:

const sortedCountries = Object.entries(Country)
  .sort(([, countryA], [, countryB]) => countryA.countryNo - countryB.countryNo)
  .map(([key, country]) => (
    <div key={country.countryNo} className="country-item">
      {/* 内容同上 */}
    </div>
  ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:24:11