首页 > 解决方案 > 我在 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

标签: javascriptreactjsaxios

解决方案


推荐阅读