【问题标题】:how to access nested object in react如何在反应中访问嵌套对象
【发布时间】:2020-01-15 01:41:12
【问题描述】:

我无法访问 react 组件中的价格。我尝试使用能够访问 imagesid 之类的对象的地图,但是在尝试访问价格值时它不起作用。我收到以下错误

地图不是{groups.map((user, index) => (user.price.map(i=><p>i.regular</p>)的函数

JSON

[
  {
    "id": "shop/new/all-new",
    "name": "All New",
    "categoryType": "subcat",
    "groups": [
      {
        "id": "modern-leaning-narrow-bathroom-shelf-h5074",
        "name": "Modern Leaning Narrow Bathroom Shelf",
        "links": {
          "www": "https://www.westelm.com/products/modern-leaning-narrow-bathroom-shelf-h5074/"
        },
        "price": { "regular": 149, "selling": 111.75, "type": "special" },
        "thumbnail": {
          "size": "m",
          "meta": "",
          "alt": "",
          "rel": "thumbnail",
          "width": 363,
          "href": "https://www.westelm.com/weimgs/ab/images/wcm/products/201952/0001/modern-leaning-narrow-bathroom-shelf-m.jpg",
          "height": 363
        },
        "hero": {

        },
        "images": [
          {  },
          {

          },
          {
                      }
        ],
        "swatches": [],
        "messages": [],
        "flags": [
       ],
        "reviews": {
         }
      },
      [..more objects]

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    groups.user.price 是一个对象,而不是一个数组,所以map 不是它的函数。相反,您可能想做类似

    的事情

    const thing = {
      "id": "shop/new/all-new",
      "name": "All New",
      "categoryType": "subcat",
      "groups": [{
        "id": "modern-leaning-narrow-bathroom-shelf-h5074",
        "name": "Modern Leaning Narrow Bathroom Shelf",
        "links": {
          "www": "https://www.westelm.com/products/modern-leaning-narrow-bathroom-shelf-h5074/"
        },
        "price": {
          "regular": 149,
          "selling": 111.75,
          "type": "special"
        },
    }]};
    
    thing.groups.map(group => Object.keys(group.price).map(priceOpt => console.log(priceOpt, group.price[priceOpt])));

    Object.keys() 将获取一个对象并为您提供所有键的数组,然后您可以调用map

    【讨论】:

      【解决方案2】:

      你不能在对象上使用地图。

      试试这个

         {groups.map((user, index) => {
            return (<div>
             {Object.keys(user.price).map(i=><p>user.price[i]</p>}
            </div>);
          }}
      

      【讨论】:

        猜你喜欢
        • 2021-12-06
        • 2020-09-02
        • 1970-01-01
        • 2022-11-09
        • 1970-01-01
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多