我似乎无法掌握循环数组/对象。我经常陷入其中。像这里一样,例如我无法从 api 迭代数据,我收到 trending is not a function
错误。有人可以帮我解决这个问题,并给我一些好的方向来更好地循环
界面
export interface Item {
id: string;
name: string;
symbol: string;
market_cap_rank: number;
thumb: string;
large: string;
score: number;
}
export interface Coin {
item: Item;
}
export interface ResponseObject{
coins: Coin[];
}
代码
import React, { useEffect, useState} from 'react'
import axios from 'axios'
import { ResponseObject } from '../interfaces';
const TRENDING = 'https://api.coingecko.com/api/v3/search/trending'
const Home:React.FC= () => {
const [trending, setTrending ] = useState<ResponseObject[]>([])
useEffect(()=>{
axios
.get<ResponseObject[]>(TRENDING)
.then((response) =>
{setTrending(response.data);
console.log(response) })
.catch(err =>
{ console.log(err); })
},[])
return (
<div>
{trending.map(trend =>
(<div key={trend.item.id}>{trend.item.name}</div>))}
</div>
)
}
export default Home
API
{
"coins":[
{
"item":{
"id":"superfarm",
"name":"SuperFarm",
"symbol":"SUPER",
"market_cap_rank":235,
"thumb":"https://assets.coingecko.com/coins/images/14040/thumb/6YPdWn6.png?1613975899",
"large":"https://assets.coingecko.com/coins/images/14040/large/6YPdWn6.png?1613975899",
"score":0
}
},
{...}
],
"exchanges":[]
}
答案 0 :(得分:1)
问题与循环无关。
您正在使用不是数组的东西调用 setTrending
。这就是您获得 trending.map is not a function
的原因。
您的 API 不是直接返回一个数组,而是一个带有两个键的对象,每个键都保存一个数组。
就您而言,您必须致电 setTrending(response.data.coins)
。
编辑:您还应该修复您的 ResponseObject
用法:
const [trending, setTrending ] = useState<Coin[]>([]);
useEffect(()=> {
axios
.get<ResponseObject>(TRENDING)
.then((response) => {
setTrending(response.data.coins);
})
.catch(err => console.log(err));
},[]);
答案 1 :(得分:1)
我猜您可能将对象设置为趋势而不是数组。 response.data
应返回一个与您的 API 相似的对象。
// response.data should return this object.
{
"coins":[
{
"item":{
"id":"superfarm",
"name":"SuperFarm",
"symbol":"SUPER",
"market_cap_rank":235,
"thumb":"https://assets.coingecko.com/coins/images/14040/thumb/6YPdWn6.png?1613975899",
"large":"https://assets.coingecko.com/coins/images/14040/large/6YPdWn6.png?1613975899",
"score":0
}
},
{...}
],
"exchanges":[]
}
您应该将 response.data.coins
设置为趋势,它将返回一个数组。
[
{
"item":{
"id":"superfarm",
"name":"SuperFarm",
"symbol":"SUPER",
"market_cap_rank":235,
"thumb":"https://assets.coingecko.com/coins/images/14040/thumb/6YPdWn6.png?1613975899",
"large":"https://assets.coingecko.com/coins/images/14040/large/6YPdWn6.png?1613975899",
"score":0
}
},
{...}
]