[英]How to access a JSON object that's already been parsed in Javascript?
我制作了这个代码沙箱来解释我遇到的问题。 我在底部添加了评论,当您将 {buyDate.id} 更改为 {buyDate.market_data.current_price.usd} 时。 你会看到我遇到的问题。 我相信它被正确获取并且控制台显示了我的期望。 这是代码沙箱: codesandbox.io/s/coingecko-api-example22-9zysm?file=/src/App.js
任何帮助将不胜感激!
以下是原帖:
我查看了类似问题的其他答案,但没有解决我遇到的问题。 这是 ReactJS。
我设置了以下变量:
const [trade, setTrade] = useState({
sellData: {},
buyData: {},
});
当我使用我想要的正确输入 console.log 购买数据时,我收到:
buyData:
{id: "bitcoin", symbol: "btc", name: "Bitcoin", image: {…}, market_data: {…}, …}
community_data: {facebook_likes: null, twitter_followers: 68912, reddit_average_posts_48h: 7.833, reddit_average_comments_48h: 270.833, reddit_subscribers: 1303941, …}
developer_data: {forks: 25238, stars: 42377, subscribers: 3497, total_issues: 5257, closed_issues: 4491, …}
id: "bitcoin"
image: {thumb: "https://assets.coingecko.com/coins/images/1/thumb/bitcoin.png?1547033579", small: "https://assets.coingecko.com/coins/images/1/small/bitcoin.png?1547033579"}
market_data:
current_price:
aed: 32711.28293095498
ars: 553792.3126161147
...
因此,当我调用应该可以工作的trade.buyData.market_data.current_price.aed
时,我收到一个TypeError: Cannot read property 'current_price' of undefined
错误TypeError: Cannot read property 'current_price' of undefined
但我希望它返回32711.28293095498
。
我尝试将 trade.buyData 的设置值从{}
更改为其他类型,例如 NaN 或 undefined。 我还尝试添加 catch 错误消息,但没有任何效果。 有一次,它无缘无故地工作了一半。
任何帮助将不胜感激。
查看您的 codeSandbox 后,很明显您在buyData
上有一个空指针,因为您将对象定义为空并尝试在渲染阶段(在这种情况下为初始渲染)访问它的属性。
您可以在代码沙箱的第 27 行的market_data
使用可选链运算符 (?.)修复它 - buyDate.market_data?.current_price.usd
return (
<div className="App">
<input defaultValue={buyDate} onChange={(val) => handleBuyChange(val)} />
{/* market_data needs to be null checked */}
{buyDate.market_data?.current_price.usd}
<h4>
The purpose of this project is to input the date and get back the
bitcoin price at the time
</h4>
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.