1

我正在尝试解析和映射此 api 响应中的数组“项目”

[
  {
    "id": "",
    "portal_account_id": "",
    "platform": "",
    "current_date": "2018-07-30T11:27:16+02:00",
    "email": "",
    "items": [
      {
        "itemId": "123",
        "name": "vacuum 1",
        "img": ""
      },
      {
        "itemId": "456",
        "name": "vacuum 2",
        "img": ""
      },
      {
        "itemId": "789",
        "name": "vacuum 3",
        "img": ""
      }
    ]
  }
]

这是我尝试过的,它只是解析响应本身,但我想解析这个响应中的数组。

this.props.items.map((item) => {
                return (
                    <Col className='' xs={12} md={4} key={item.id}>
                        <ProductItem handleOnAdd={this.dispachAddToCart.bind(this)} item={item} />
                    </Col>
                );
            })
4

3 回答 3

0

你的意思是你只想解析响应数组的第一项:

this.props.items[0].items.map
于 2018-09-02T17:46:55.840 回答
0

假设这是你的数组;

const response = [
  {
    "id": "",
    "portal_account_id": "",
    "platform": "",
    "current_date": "2018-07-30T11:27:16+02:00",
    "email": "",
    "items": [
      {
        "itemId": "123",
        "name": "vacuum 1",
        "img": ""
      },
      {
        "itemId": "456",
        "name": "vacuum 2",
        "img": ""
      },
      {
        "itemId": "789",
        "name": "vacuum 3",
        "img": ""
      }
    ]
  },
  {
    "id": "",
    "portal_account_id": "",
    "platform": "",
    "current_date": "2018-07-30T11:27:16+02:00",
    "email": "",
    "items": [
      {
        "itemId": "123",
        "name": "vacuum 1",
        "img": ""
      },
      {
        "itemId": "456",
        "name": "vacuum 2",
        "img": ""
      },
      {
        "itemId": "789",
        "name": "vacuum 3",
        "img": ""
      }
    ]
  }
];

然后在render方法中执行此操作。

render() {
   return (
      {response.map(item => {
          return (
             <div key={item.id}>
                {item.items.map(product => {
                    return (
                       <div key={product.itemId}>
                          <p>{product.name}</p>
                          <p>path of image{product.img}</p>
                       </div>
                    );
                })}
             </div>
          )
      })}
   );
}

问题是你得到一个对象数组,每个对象内部还有另一个对象数组。

于 2018-09-02T17:37:38.370 回答
0

您可能正在从您的 API 获取 JSON res。您可以对其进行破坏items,然后对其进行迭代。

render(){
const { items } = this.props.response

 items.map((item)=>{
    return (
      // do the stuff here
    )
   })

}
于 2018-09-02T16:30:18.413 回答