【发布时间】:2021-06-01 00:22:34
【问题描述】:
美好的一天,我有一个项目从 API 获取响应,然后将数据从父级传递给子级。问题是,我可以轻松访问顶层的响应,但是当我尝试进入 API 的内部部分(在本例中为 price={statistics.quotes.USD.price})时,我收到了 TypeError: Cannot read property 'USD' of undefined 错误。我已经尝试过控制台。记录价格以检查我的路径是否正确。当我可以正确访问其他数据时,为什么会发生这种情况?
Overview.js
import React, { useState, useEffect } from 'react';
import Statistics from './Statistics';
import axios from 'axios';
export default function Overview(props) {
const id = props.match.params.currency;
//some other states here
const [statistics, setStatistics] = useState({});
//some code
const fetchBasicData = async () => {
// Retrieves a coin's basic information
const apiCall = await axios.get('https://api.coinpaprika.com/v1/coins/' + id);
let basicData = await apiCall.data;
setCoin(basicData);
// Retrieves coin statistics
const fetchedData = await axios.get('https://api.coinpaprika.com/v1/tickers/' + id);
const coinStats = await fetchedData.data;
setStatistics(coinStats);
}
useEffect(function () {
if (Object.keys(coin).length === 0 && Object.keys(statistics).length === 0) {
fetchBasicData();
}
})
//some code
return (
<div>
//some other stuff
<Statistics
statistics={statistics}
lastUpdate={statistics.last_updated}
price={statistics.quotes.USD.price} // <----- this is where the error occurs
/>
</div>
);
}
Statistics.js
import React from 'react';
export default function Statistics(props) {
return (
<div>
<h1>Statistics</h1>
<p>Last updated: {props.lastUpdate}</p>
<p>Price: {props.price}</p>
<p>Market Rank: {props.marketRank}</p>
<h2>Supply</h2>
<p>Circulating supply: {props.circulatingSupply}</p>
<p>Max supply: {props.maxSupply}</p>
</div>
);
}
【问题讨论】:
-
查看实际的 JSON 响应会很有用。命名约定“引号”让我觉得它应该是一个数组——即使它只有一个对象,所以你需要访问正确的索引。但错误暗示
quotes未定义 -
这是来自 API 的示例响应(ID 为“eth-ethereum”)。 ibb.co/XCCrRRH我可以轻松访问名称、符号等。但是当我尝试访问价格时却卡住了。
标签: javascript json reactjs frontend typeerror