React调用Coingecko API报错TypeError: Cannot read properties of undefined (reading 'map')
问题根因
- 第一个报错
TypeError: Cannot read properties of undefined (reading 'map')是因为CoinGecko的/exchange_rates接口返回的根对象不存在data字段,你写setCrypData(res.data)相当于给crypData赋值了undefined,调用undefined.map自然会报错。 - 第二个报错
TypeError: crypData.map is not a function是因为你直接把接口返回的根对象赋值给了crypData,map是数组专属方法,普通对象没有这个方法,所以触发报错。
修复方案
首先明确该接口的返回结构:
{ "rates": { "btc": {"name":"Bitcoin","unit":"BTC","value":1,"type":"crypto"}, "eth": {"name":"Ethereum","unit":"ETH","value":15.324,"type":"crypto"}, // 其余币种键值对 } }
你需要把rates字段对应的键值对对象转换为数组,才能使用map遍历,同时调整渲染逻辑,不需要再嵌套取rates.btc相关属性,遍历的每一项就是单个币种的完整信息。
修正后完整代码
import { useState, useEffect } from 'react'; const DataTables = () => { const [crypData, setCrypData] = useState([]); const apiGet = () => { fetch('https://api.coingecko.com/api/v3/exchange_rates') .then(response => { if(response.ok){ return response.json() } throw response; }) .then(res => { // 将rates对象转为数组后赋值 setCrypData(Object.values(res.rates)); }); }; useEffect(() => { apiGet(); }, []) return ( <> {/* 加可选链防止数据未返回时调用map报错,同时给列表项加key属性符合React规范 */} {crypData?.map((item, index) => <tr key={index}> <td scope="row">{item.name}</td> <td>{item.unit}</td> <td>{item.value}</td> <td> {item.type} <button type="button"></button> </td> </tr> )} </> ); } export default DataTables;
内容的提问来源于stack exchange,提问作者Paul Barasa
相关产品推荐
相关产品推荐

