【问题标题】:mapping through array of objects通过对象数组映射
【发布时间】:2019-11-21 08:44:32
【问题描述】:

我正在尝试映射以下数据并返回“余额”,但它一直告诉我“编码”未定义。

这里是数组

"entry": [
    {
      "resource": {
        "id": "1980438",
        "type": {
          "coding": [
            {
              "system": "https://www.medeo-health.com/uploads/1/1/8/1/118121028/s491564155970805143-c3-i1-w640_orig.jpeg",
              "code": "25062444",
              "display": "Balance"
            }
          ]
        },
        "manufactureDate": "2017-01-08",
        "expirationDate": "2020-01-08",
        "owner": {
          "reference": "Organization/1980437"
        }
      },
      "search": {
        "mode": "match"
      }
    }, ...

这就是我正在尝试的:

import React, { Component } from 'react';

import Device from './Device/Device';
import axios from 'axios';

class Devices extends Component {
    state = {
        devices: null
    }

    componentDidMount() {
        axios.get('http://hapi.fhir.org/baseDstu3/Device?organization=1980437&_include=Device:organization&_sort=device-name')
            .then(res => {
                this.setState({ devices: res.data.entry });
            })
            .catch(error => {
                console.log(error);
            })
    }

    render() {

        let devices = <p style={{ textAlign: "left", margin: "0" }}>This practitioner have no devices!</p>;
        if (this.state.devices) {
            devices = this.state.devices.map(device => {
                return (
                    <Device
                        key={device.resource.id}
                        name={device.resource.type.coding[0].display}
                    />
                )
            });
        }
        return (
            <div>
                {devices}
            </div>
        );
    };
};

export default Devices;

id 返回良好,但对于名称,它不断收到“无法读取未定义的属性'编码'”

我做错了什么?

【问题讨论】:

  • 根据给定的信息,它找不到“类型”变量。你能创建一个沙盒给我看吗?

标签: javascript reactjs


【解决方案1】:

得到了问题。您收到 undefined 是因为您收到的最后一个对象不包含 type 属性。请检查

试试这样的东西

 {this.state.devices.map(device => {
      if (device.resource.type) { //check type property exists first then render
        console.log(device.resource.type.coding[0].display);
        return (
          <p key={device.resource.id}>
            {device.resource.type.coding[0].display}
          </p>
        );
      } else return null;
    })}

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2020-10-24
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多