react/api - 如何解析和映射 api 响应中的数组

react/api - how to parse and map an array inside of api response

我正在尝试通过此 api 响应

内的数组 "items" 进行解析和映射
[
  {
    "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>
                );
            })

您可能正在从 API 获得 JSON 资源。您可以从中析构 items,然后对其进行迭代。

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

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

}

假设这是你的数组;

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>
          )
      })}
   );
}

问题是您获得了一个对象数组,而每个对象内部都有另一个对象数组。

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

this.props.items[0].items.map