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

如何在React中遍历对象并渲染HTML元素(类似Array.map)

如何在React中遍历对象并渲染HTML元素?

我之前用JavaScript数组的**map()**方法遍历数组,在React里渲染HTML元素。比如针对数组["Mike", "David", "Peter", "Steve"],对应的React代码是:

const RenderNames = () => {
  let names = ["Mike", "David", "Peter", "Steve"];

  const renderNames = (allNames) => {
    return allNames.map((name) => {
      return <div>hello {name}</div>;
    });
  };
  
  return (
    <div>{renderNames(names)}</div>
  );
};

现在我把数组改成了键值对对象:{"243fx": "Mike", "g3Frt": "David", "8879a": "Peter", "dkr45": "Steve"},请问该怎么遍历这个对象并渲染对应的HTML元素?


解决方案

对象不能直接用map()方法,需要先把它转换成数组,再用map()遍历。常用的两种方式如下:

1. 只需要渲染对象的值(名字)

用Object.values()方法提取对象的所有值,得到一个数组后再用map():

const RenderNames = () => {
  let names = {"243fx": "Mike", "g3Frt": "David", "8879a": "Peter", "dkr45": "Steve"};

  const renderNames = (allNames) => {
    return Object.values(allNames).map((name, index) => {
      // 索引作为key是备选方案,优先用对象的唯一键(见下方方法)
      return <div key={index}>hello {name}</div>;
    });
  };
  
  return (
    <div>{renderNames(names)}</div>
  );
};

2. 同时用到对象的键和值(推荐,满足React的key要求)

用Object.entries()方法把对象转换成[键, 值]组成的数组,这样既能拿到名字,又能把唯一的键作为React元素的key(避免列表渲染警告):

const RenderNames = () => {
  let names = {"243fx": "Mike", "g3Frt": "David", "8879a": "Peter", "dkr45": "Steve"};

  const renderNames = (allNames) => {
    return Object.entries(allNames).map(([key, name]) => {
      return <div key={key}>hello {name}</div>;
    });
  };
  
  return (
    <div>{renderNames(names)}</div>
  );
};

注意事项

React渲染列表时,必须给每个元素添加唯一的key属性,这能帮助React高效更新DOM。用对象自带的唯一键作为key是最优选择,比用数组索引更可靠(索引会在元素顺序变化时导致渲染异常)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:10:32