【问题标题】:Error in working with useEffect for fetching data from an API使用 useEffect 从 API 获取数据时出错
【发布时间】:2022-01-22 13:25:18
【问题描述】:

我正在学习 React Native,在关注 YouTube 上的实时编码课程之一时,我遇到了以下问题。 我想做的是:我正在制作一个带有 expo 的应用程序,我想从 CoinGecko's free crypto API 获取数据。我的代码是:

import React, { useState, useEffect } from "react";
import { View, Text, Image } from "react-native";
import axios from "axios";
const getCoinData = async (coinId) => {
  try {
    const response = await axios.get(
      `https://api.coingecko.com/api/v3/coins/${coinId}?community_data=false&developer_data=false`
    );
    return response.data;
  } catch (error) {
    console.log(error);
  }
};
const BugScreen = () => {
  const [coin, setCoin] = useState(null);

  useEffect(() => {
    const fetchCoinData = async () => {
      const fetchedCoinData = await getCoinData("bitcoin");
      setCoin(fetchedCoinData);
    };
    fetchCoinData();
  }, []);

  const {
    name,
    symbol,
    image: { small },
    market_cap_rank,
  } = coin;

  return (
    <View style={{ paddingHorizontal: 10 }}>
      <Text>{name}</Text>
      <Text>{symbol}</Text>
      <Image source={{ uri: small }} style={{ height: 25, width: 25 }} />
      <Text>{market_cap_rank}</Text>
    </View>
  );
};

export default BugScreen;

我收到一条错误消息,告诉我 null 不是对象(评估 'coin.name'。我还加入了Screenshot of the error

我理解的方式是每次渲染屏幕时,useEffect() 应该运行并获取数据,但奇怪的是,即使我添加了一个 'console.log(coin) in the body of the 'fetchCoinData 函数,控制台的屏幕上没有写任何内容。

如果您能帮助我了解发生了什么问题,您将非常感激。谢谢。

【问题讨论】:

    标签: react-native react-hooks axios expo use-effect


    【解决方案1】:

    您将 coin 初始化为 null,因此在 API 调用解决之前,它仍然是 null

    也许更好的选择是将其初始化为占位符对象

    const initialState = {
      name: "",
      symbol: "",
      image: {
        small: "https://via.placeholder.com/150"
      },
      market_cap_rank: ""
    }
    
    const BugScreen = () => {
      const [coin, setCoin] = useState({...initialState});
    
      // etc
    

    【讨论】:

      【解决方案2】:

      感谢您的帮助。根据@Phil 的评论,我做了以下事情并且成功了:

      import React, { useState, useEffect } from "react";
      import { View, Text, Image } from "react-native";
      import axios from "axios";
      
      const getCoinData = async (coinId) => {
        try {
          const response = await axios.get(
            `https://api.coingecko.com/api/v3/coins/${coinId}?community_data=false&developer_data=false`
          );
          return response.data;
        } catch (error) {
          console.log(error);
        }
      };
      
      const BugScreen = () => {
        const initialState = {
          name: "",
          symbol: "",
          image: "https://via.placeholder.com/150",
          marketCapRank: "",
        };
        const [coin, setCoin] = useState(initialState);
      
        useEffect(() => {
          const fetchCoinData = async () => {
            const fetchedCoinData = await getCoinData("bitcoin");
            const fetchedData = {
              name: fetchedCoinData.name,
              symbol: fetchedCoinData.symbol,
              image: fetchedCoinData.image.small,
              marketCapRank: fetchedCoinData.market_cap_rank,
            };
            setCoin((coin) => {
              return { ...coin, ...fetchedData };
            });
          };
          console.log(coin);
          fetchCoinData();
        }, []);
      
        const { name, symbol, image, marketCapRank } = coin;
      
        return (
          <View style={{ paddingHorizontal: 10 }}>
            <Text style={{ color: "white" }}>{name}</Text>
            <Text style={{ color: "white" }}>{symbol}</Text>
            <Image source={{ uri: image }} style={{ height: 25, width: 25 }} />
            <Text style={{ color: "white" }}>{marketCapRank}</Text>
          </View>
        );
      };
      
      export default BugScreen;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-20
        • 2023-01-31
        • 2022-11-02
        • 2021-06-19
        相关资源
        最近更新 更多