【发布时间】:2021-03-11 06:10:51
【问题描述】:
我正在尝试通过使用提取的信息更新我的状态来从 api 获取加密货币数据。但是当我这样做时,我的 console.log 显示一个空对象。也没有数据传递给我的子组件。我在这里做错了吗?
import React, {useState, useEffect} from 'react';
import SmallBox from './SmallBox';
import './App.css';
function App() {
const [smallData, setSmallData] = useState({})
async function getAPI(){
await fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false
`)
.then(response => response.json())
.then(data => setSmallData({data}));
}
useEffect( () => {
getAPI();
console.log(smallData)
}, []);
return (
<div className="app">
{/* SmallBox - balance */}
<SmallBox className="balance"/>
{/* SmallBox - bitcoin */}
<SmallBox className="bitcoin" coin={smallData}/>
{/* SmallBox - ethereum */}
<SmallBox className="ethereum" coin={smallData}/>
{/* SmallBox - ripple */}
<SmallBox className="ripple" coin={smallData}/>
{/* SmallBox - tether */}
<SmallBox className="tether" coin={smallData}/>
</div>
);
}
export default App;
【问题讨论】:
-
getAPI是一个async函数。当您调用console.log时,状态尚未更新。 -
您的 API 调用和响应状态更改都是异步的,您可以在下一行打印状态值并查看更新
标签: reactjs api react-hooks jsx