You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native中输出Fetch请求响应并展示在Text组件中

在React Native中展示Fetch请求的响应内容

要实现打印Fetch响应并在Text组件中展示的需求,你可以借助React的状态管理和副作用处理Hook来修改代码,具体实现如下:

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';

function Nft() {
  // 初始化状态:存储比特币价格、加载状态、错误信息
  const [bitcoinPrice, setBitcoinPrice] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 发起Fetch请求
    fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd")
      .then(response => {
        // 检查响应是否成功
        if (!response.ok) {
          throw new Error('请求失败');
        }
        return response.json();
      })
      .then(data => {
        // 提取并更新比特币价格
        setBitcoinPrice(data.bitcoin.usd);
        setLoading(false);
        // 控制台打印响应内容
        console.log('Fetch响应内容:', data);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
        console.error('请求错误:', err);
      });
  }, []); // 空依赖数组确保组件挂载时只执行一次请求

  return (
    <View style={styles.container}>
      <Text style={styles.header}>Bitcoin Price</Text>
      {/* 根据状态渲染对应内容 */}
      {loading && <Text>加载中...</Text>}
      {error && <Text>错误:{error}</Text>}
      {bitcoinPrice && <Text>当前价格:${bitcoinPrice}</Text>}
    </View>
  );
}

// 样式定义
const styles = StyleSheet.create({
  container: {
    padding: 20,
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
  },
  header: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 10,
  },
});

export default Nft;

核心要点说明:

  • 状态管理:用useState创建三个状态变量,分别存储价格数据、加载状态和错误信息,确保UI能随数据变化实时更新。
  • 副作用处理:useEffect用于在组件挂载时发起Fetch请求,空依赖数组[]保证请求只执行一次。
  • 请求处理:通过.then解析响应的JSON数据,提取比特币价格并更新状态;用.catch捕获请求异常,同时在控制台打印响应或错误信息。
  • UI渲染:根据loading、error、bitcoinPrice的状态,分别显示加载提示、错误信息或最终的价格数据,优化用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:20:37