简体   繁体   English

如何在反应中访问嵌套对象的某些元素

[英]How to access certain element of nested objects in react

I'm struggling to take certain value out of an API.我正在努力从 API 中获取某些价值。 I have no trouble mapping over the parts that I can immediately access using items.value, but when I can't get some of the more nested info.我可以毫无问题地映射我可以使用 items.value 立即访问的部分,但是当我无法获得一些更嵌套的信息时。 I'm specifically trying to access the value of "quantity" inside of pricing.我特别试图在定价中访问“数量”的价值。 Here's my code这是我的代码

import "./StoreDisplay.css"


    class StoreDisplay extends Component {
    constructor(props) {
  super(props)

  this.state = {
     error: undefined,
     isLoaded: false,
     items: []

  }
}


componentDidMount() {
    this.getData();
  }

  getData() {
    fetch(url)
    .then((res) => res.json())
    .then(
      (result) => {
        this.setState({
          isLoaded: true,
          items: result,

        });
        console.log(result)
      },
      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    );
 }



     render() {

      const { error, isLoaded, items } = this.state;
      if (error) {
        return <div>Error: {error.message}</div>;
      } else if (!isLoaded) {
        return <div>Loading...</div>;
      } else {
        return (
          <div id = "storeDisplay">
            <ul className = "container">
              {items.map(item => (
                <li key = {item.title}>
                  <div className = "bundleName"> {item.title} {item.pricing.quantity}</div><img src = {item.asset} className = "img"></img>
                </li>
              ))}
            </ul>
          </div>
        );
      }
    }
  }

Sample part of JSON from API:来自 API 的 JSON 的样本部分:

 [
    {
        "title": "100-Pack Bundle",
        "desc": "",
        "tag": "",
        "purchaseLimit": 1,
        "isAvailable": true,
        "expireTimestamp": 1662538288,
        "shopType": "specials",
        "originalPrice": 10500,
        "pricing": [
            {
                "ref": "Apex Coins",
                "quantity": 6700
            }
        ],
        "content": [
            {
                "ref": "weapon_charm_charm_apex_asset_v22_misc_pathfinderemoji01",
                "name": "MRVN Monitor",
                "quantity": 1
            },
            {
                "ref": "pack_cosmetic_rare",
                "name": "Apex Pack",
                "quantity": 100
            }
        ],
        "offerID": "220823_100-pack_bundle",
        "asset": "https:\/\/shop-cdn.mozambiquehe.re\/dl_store_s14_0_bund_epic_100pack_a189.png"
    },

It looks like item.pricing is actually an array of objects.看起来item.pricing实际上是一个对象数组。 From here you have a couple of choices, depending on what you want to do.从这里你有几个选择,这取决于你想做什么。

  1. item.pricing will only ever have one element. item.pricing永远只有一个元素。
    In this case, you can just take the first element:在这种情况下,您可以只取第一个元素:
     <div className = "bundleName"> {item.title} {item.pricing[0].quantity}</div>
  2. You want to list all the quantities您想列出所有数量
    <div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).join(" ")}</div>
    or或者
    <div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).join(", ")}</div>
  3. You want to have the sum of all quantities你想要所有数量的总和
    <div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).reduce((a, b) => a + b, 0)}</div>

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

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