我对Typescript有点陌生。这里我有一个简单的API,我想迭代并显示数据。您可以访问API链接并查看原始数据。如果能给我一些帮助,我将不胜感激。
接口:
export interface ITrending {
coins: IItem[]
}
export interface IItem {
item: {
id: string;
name: string;
symbol: string;
market_cap_rank: number;
thumb?: string;
large?: string
}
}
反应代码:
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { ITrending } from '../interfaces'
const TRENDING = 'https://api.coingecko.com/api/v3/search/trending'
const Home = () => {
const [trending, setTrending] = useState<ITrending[]>([])
useEffect(() => {
axios.get<ITrending[]>(TRENDING).then((response) => {
setTrending(response.data)
console.log(response.data)
})
}, [])
return <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":[]
}
由于硬币在data.coins
内部,您需要使用以下方式:
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { ITrending } from '../interfaces'
const TRENDING = 'https://api.coingecko.com/api/v3/search/trending'
const Home = () => {
const [trending, setTrending] = useState<ITrending[]>([])
useEffect(() => {
axios.get<ITrending[]>(TRENDING).then((response) => {
setTrending(response.data.coins)
console.log(response.data)
})
}, [])
return <div>{trending.map(t => (<div key={t.item.id}>{t.item.name}</div>)}</div>
}
export default Home