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

React中映射对象数组报currencyList.map is not a function错怎么办

报错原因

调用.map()时报currencyList.map is not a function错误的核心原因是:接口返回的res.data['results']是键值对结构的普通对象,不是数组类型。.map()是数组原型上的遍历方法,仅支持在数组实例上调用,直接对普通对象调用就会触发该报错。
从你打印的接口数据可以看出,返回结果的结构是「货币代码作为键、货币详情作为值」的普通对象,本身不具备数组的遍历方法。

修正步骤
  • 调整state初始值:将currencyList的初始值设为空数组,省去额外的判空逻辑,空数组调用.map()不会触发报错。
  • 数据格式转换:拿到接口返回的对象后,用JS原生对象方法将其转为数组格式再存入state。
  • 调整渲染逻辑:遍历过程中不要直接渲染整个对象,要读取对象内的具体字段输出,同时给列表项添加唯一key属性,避免React渲染警告。
修正后完整代码
const [currencyList, setCurrencyList] = useState([]);

useEffect(() => {
  axios.get(listOfCurrencies)
  .then(res => {
    // 提取对象中所有货币详情值,转为数组格式
    const currencyArr = Object.values(res.data['results']);
    setCurrencyList(currencyArr);
  })
  .catch(error => {
    console.log("there was an error with connecting to database")
  })
}, []);

return (
  <div>
    <h1> 货币列表 </h1>
    {currencyList.map(curr => (
      <div key={curr.id}>
        <div>货币代码:{curr.id}</div>
        <div>货币名称:{curr.currencyName}</div>
        {curr.currencySymbol && <div>货币符号:{curr.currencySymbol}</div>}
      </div>
    ))}
  </div>
)

可选扩展

如果你需要在渲染时拿到作为对象键的货币代码,可以用Object.entries做格式转换:

const currencyArr = Object.entries(res.data['results']).map(([currencyCode, detail]) => {
  return {
    currencyCode,
    ...detail
  }
});

转换后数组的每个元素都会额外带上currencyCode字段,渲染时直接读取即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:12:32