【发布时间】: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