javascript - 我在 reactjs 中使用 axios 从 api 调用中检索值时遇到问题
问题描述
您好,我开始学习使用 Axios 从 API 获取数据以用于我的 Reactjs 组件。
我有以下代码:
function getCryptoZoonPrice ()
{
let price = 0;
axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=cryptozoon&order=market_cap_desc&per_page=100&page=1&sparkline=false')
.then(res => {
res.data.map(coin => (price = coin.current_price))
})
return price;
}
const Chart = () => {
const [chartData, setChartData] = useState({});
const chart = () => {
let earnDay = [];
let earnZoon = [];
axios
.get("http://localhost:4000/api/earnings")
.then(res => {
for (const dataObj of res.data) {
earnDay.push(moment(dataObj.createdAt).format('ll'));
earnZoon.push(parseInt(getCryptoZoonPrice() * dataObj.zoon));
}
setChartData({
labels: earnDay,
datasets: [
{
label: "Zoon a USD",
data: earnZoon,
backgroundColor: ["rgba(255, 109, 0, 1)"],
borderWidth: 4
}
]
});
})
.catch(err => {
console.log(err);
});
};
useEffect(() => {
chart();
}, []);
我不知道下一步该怎么做:-从 coingecko 的 api 返回令牌的价格,以便我可以在 const Chart 中使用,具体在这里:
earnZoon.push(parseInt(getCryptoZoonPrice() * dataObj.zoon));
此函数getCryptoZoonPrice()返回值 0
解决方案
推荐阅读
- php - php sql将ID和文本导入testarea,然后在对文本进行更改后发布这两个值
- android - 我能否使用 React Native 框架在 Mountain Lion 中编写/发布 iOS 和 Android 应用程序?
- python - 试图从不位于类内但位于脚本中的网站作为变量抓取信息
- java - Number 类如何工作(在 java 中)?
- angular - 将数据从一个可观察对象传递到另一个对象的正确方法
- css - Vuetify Container 最大宽度固定
- python - 基于变量值的自定义绘图标记
- php - 如何在 PHP/cURL/Guzzle 上使用 --preproxy
- angular - 带有引导程序 4.1 的 Angular 6 未加载
- java - 转换 java.util.Set 的
对象到简单的 pojo 对象