简体   繁体   English

无法从React组件访问嵌套的JSON数据

[英]Unable To Access Nested JSON Data from React Component

I have a map function that renders JSON data retrieved like this: 我有一个map函数,它呈现检索到的JSON数据,如下所示:

  <div className="items">
    {items.map(item =>
        <Card key={item.id} price={item.title} />)}
  </div>

It successfully iterates over and renders data from un-nested properties, but I am having trouble getting it to render the USD nested prop as shown here: 它可以成功地迭代并从未嵌套的属性呈现数据,但是我很难让它呈现美元嵌套的道具,如下所示:

     "price":{  
        "amounts":{  
           "GBP":"£8,185",
           "USD":"$12,000",
           "EUR":"€10.755"
        },

I am trying to extract it like this: 我试图像这样提取它:

  <div className="items">
    {items.map(item =>
        <Card key={item.id} price={item.price.amounts.USD} />)}
  </div>

And the error message I'm getting is "TypeError: Cannot read property 'amounts' of null." 我收到的错误消息是“ TypeError:无法读取null的属性'amounts'。” I have also tried with square brackets to no success. 我也尝试使用方括号未成功。

As you mentioned in comments, some of the price values are null (all the item doesn't contains the price object), thats why it is throwing error: 正如您在评论中提到的,某些价格值是null(所有商品均不包含price对象),这就是为什么它引发错误:

Cannot read property 'amounts' of null. 无法读取null的属性“数量”。

Solution is, put the check before accessing the amount property, Like this: 解决的方法是,在访问amount属性之前放入支票,就像这样:

price={item.price? (item.price.amounts||{}).USD||0 : 0}

Although the answer above is 100% correct (and recommended) I would consider using _.get if you are already using lodash: 尽管上面的答案是100%正确(并建议), _.get 如果您已经在使用lodash,我会考虑使用_.get:

import get from 'lodash/get'

// in render
// the third argument is the default price is *any* of the path is not defined
price={ get(item, 'price.amounts.USD', 0) }

For me, the pathing system in lodash (get, has, set) are extremely expressive and result in much more readable code. 对我而言,lodash中的路径系统(get,has,set)具有极强的表现力,并且代码更具可读性。 If you are importing just get (using the above import, instead of import { get } from lodash ) the size footprint is also quite small. 如果要导入的只是get (使用上述导入,而不是import { get } from lodash ),则尺寸占用也非常小。

Update: 更新:

An interesting comment by @SimianAngel - 100% correct regarding the default value. @SimianAngel一个有趣的评论-关于默认值100%正确。 0 is probably not what you want as a default value! 0可能不是您想要的默认值! Depending on your business logic of course. 当然取决于您的业务逻辑。

Again leveraging the path methods of lodash, creating something readable and expressive is quite simple: 再次利用lodash的path方法,创建可读性和表达性很简单的方法:

import get from 'lodash/get'
import has from 'lodash/has'

// in render
<div>
  {has(item, 'price.amounts.USD')) 
    ? <Card key={item.id} price={get(item, 'price.amounts.USD'} />
    : <div>This item isn't available in this region</div>
  }
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM