TypeError Невозможно прочитать свойство country_code со значением null - PullRequest
1 голос
/ 13 июля 2020

Я использую React для визуализации таблицы на основе вызова API, который возвращает JSON данные.

Я получаю TypeError, потому что он не может прочитать объект местоположения, и я не могу понять почему.

Я перечислил ошибку, код и вывод JSON ниже. Все остальные поля отображаются успешно.

Ошибка

TypeError Cannot read property 'country_code' of null

<td>{host.ip_addresses[0].location.country_code}</td>

Код

import React, { useState, useEffect } from "react";

import { Table } from "react-bootstrap";

const ResultTableNew = () => {
  const [hosts, setHosts] = useState<any[]>([]);

  useEffect(() => {
    fetch("https://localhost/domain/example.com/hosts")
      .then(results => results.json())
      .then(data => {
        setHosts(data);
      });
  }, []);

  return (
    <div>
      <Table variant="dark" responsive striped hover>
        <thead>
          <tr>
            <th>Hostname</th>
            <th>IPs</th>
            <th>Location</th>
            <th>ISP</th>
            <th>ASN</th>
          </tr>
        </thead>
        <tbody className="data">
          {hosts.map(host => (
            <tr key={host.name}>
              <td>{host.name}</td>
              <td>
                {host.ip_addresses.map((ip: any) => (
                  <div key={ip.ip}>{ip.ip}</div>
                ))}
              </td>
              <td>
                {host.ip_addresses.map((ip: any) => (
                  <div key={ip.reverse_dns}>{ip.reverse_dns}</div>
                ))}
              </td>

              <td>{host.ip_addresses[0].location.country_code}</td>
              <td>{host.ip_addresses[0].isp}</td>
              <td>{host.ip_addresses[0].asn}</td>
            </tr>
          ))}
        </tbody>
      </Table>
    </div>
  );
};

export default ResultTableNew;

JSON

[
    {
        "name": "library.example.com",
        "ip_addresses": [
            {
                "ip": "10.0.0.10",
                "reverse_dns": "library.example.com.",
                "location": {
                    "city": "Charlottesville",
                    "region_code": "VA",
                    "region_name": "Virginia",
                    "country_code": "US",
                    "country_name": "United States",
                    "continent_code": "NA",
                    "continent_name": "North America",
                    "latitude": 38.0370483398438,
                    "longitude": -78.517951965332
                },
                "isp": "Amazon, Inc.",
                "asn": 225
            }
        ]
    },
    {
        "name": "arts.example.com",
        "ip_addresses": [
            {
                "ip": "10.0.0.2",
                "reverse_dns": null,
                "location": {
                    "city": "Manhattan",
                    "region_code": "NY",
                    "region_name": "New York",
                    "country_code": "US",
                    "country_name": "United States",
                    "continent_code": "NA",
                    "continent_name": "North America",
                    "latitude": 40.7589111328125,
                    "longitude": -73.9790191650391
                },
                "isp": "Digitalocean LLC",
                "asn": 14061
            }
        ]
    }
]

1 Ответ

0 голосов
/ 13 июля 2020

Я бы рекомендовал использовать loda sh

npm i --save lodash

Вы можете импортировать его как

import _ from 'lodash';

И в своем коде

return (
<div>
  <Table variant="dark" responsive striped hover>
    <thead>
      <tr>
        <th>Hostname</th>
        <th>IPs</th>
        <th>Location</th>
        <th>ISP</th>
        <th>ASN</th>
      </tr>
    </thead>
    <tbody className="data">
      {hosts.map(host => (
        <tr key={host.name}>
          <td>{host.name}</td>
          <td>
            {host.ip_addresses.map((ip: any) => (
              <div key={ip.ip}>{ip.ip}</div>
            ))}
          </td>
          <td>
            {host.ip_addresses.map((ip: any) => (
              <div key={ip.reverse_dns}>{ip.reverse_dns}</div>
            ))}
          </td>

          <td>{_.get(host, "ip_addresses[0].location.country_code", "")}</td>
          <td>{host.ip_addresses[0].isp}</td>
          <td>{host.ip_addresses[0].asn}</td>
        </tr>
      ))}
    </tbody>
  </Table>
</div>
);
};

Таким образом он никогда не вызовет исключения. Вы также можете указать значение по умолчанию в третьем параметре функции _.get.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...