You need to enable JavaScript to run this app. React Native中如何正确执行axios请求并渲染返回的接口数据?
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何正确执行axios请求并渲染返回的接口数据?

问题根因

  • goForAxios是异步函数,调用后返回的是Promise实例而非接口返回的数值,你直接把Promise对象传入round方法做数值运算,自然会返回NaN
  • React组件渲染是同步执行逻辑,不能直接在组件顶层调用异步方法拿返回值直接用于渲染,需要配合状态钩子和副作用钩子实现异步数据更新渲染

修正后的代码

import React, { useEffect, useState } from "react";
import { Text } from "react-native";
import axios from "axios";

function round(num) {
  var m = Number((Math.abs(num) * 100).toPrecision(15));
  return (Math.round(m) / 100) * Math.sign(num);
}

const goForAxios = async (coin) => {
  const response = await axios.get(
    `https://min-api.cryptocompare.com/data/price?fsym=${coin}&tsyms=INR`
  );
  return response.data.INR;
};

export default function MarketPrice(props) {
  const [price, setPrice] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 每次传入的币种变化时重新请求价格
    const fetchPrice = async () => {
      setLoading(true);
      try {
        const res = await goForAxios(props.coin);
        setPrice(res);
      } catch (err) {
        console.error('价格获取失败', err);
        setPrice(null);
      } finally {
        setLoading(false);
      }
    };
    fetchPrice();
  }, [props.coin]);

  if (loading) return <Text>加载中...</Text>;
  if (price === null) return <Text>价格获取失败</Text>;
  return <Text>{round(price)}</Text>;
}

核心改动说明

  • 新增price状态存储接口返回的价格数值,loading状态管理请求过程中的展示逻辑
  • 通过useEffect监听props.coin的变化,每次币种更新就触发新的价格请求,请求成功后把数值更新到price状态,状态变更会触发组件重新渲染拿到最新值
  • 去掉了goForAxios里的toString转换,直接返回数值给round方法做运算,避免多余的类型转换问题

内容的提问来源于stack exchange,提问作者uday

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 09:45:07