【问题标题】:TypeError: Cannot read property 'name' of undefined - Fetching data from restcountries APITypeError:无法读取未定义的属性“名称” - 从 restcountries API 获取数据
【发布时间】:2021-06-15 10:40:44
【问题描述】:

我正在根据来自frontendmentor 的 Rest Country API 挑战构建一个应用程序。我遇到了一个问题。尝试使用 alpha3code 查找边境国家全名时,出现错误: TypeError: Cannot read property 'name' of undefined.

import React, { useState, useEffect } from "react";
import axios from "axios";
import {Link} from "react-router-dom";
import {CountryDetailStyles, ImgContainer, CountryInfo, CountryInfoDetails, CountryDetailsWrapper, CountryInfoDetailsInner, CountryBorders, LinkWrapper} from "../styles/CountryDetailStyles";

function CountryDetail({match}) {
  useEffect(() => {
     fetchItem();
      
  }, []);

  useEffect(() => {
     setBorderCountries();
  }, []);

  const [item, setItem] = useState([]);
  const [allCountries, setAllCountries] = useState([]);

  const fetchItem = async () => {
    const response = await axios.get(`https://restcountries.eu/rest/v2/name/${match.params.name}?fullText=true`);
    setItem(response.data)
  }

  const setBorderCountries = async () => {
    const response = await axios.get(`https://restcountries.eu/rest/v2/all`);
    setAllCountries(response.data)
  }

  // get borders full name using alpha3code
  const getBorderCountryName = (allCountries, border) => {
    const matchingCountry = allCountries.find(country => {
      return country.alpha3Code === border;
    })

    return matchingCountry.name;
  }

    
  return (
       <CountryDetailStyles>
           <Link className="country-links" to={"/"}>
             <LinkWrapper>
             <p><i className="fas fa-arrow-left"></i>Go Back</p>
             </LinkWrapper>
             </Link>
           {item.map(i => (   
               <CountryDetailsWrapper>           
               <ImgContainer flag={i.flag}>
               </ImgContainer>
               <CountryInfo>
                   <h1>{i.name}</h1>
                   <CountryInfoDetails>
                       <CountryInfoDetailsInner>
                       <p><span>Native Name: </span>{i.nativeName}</p>
                       <p><span>Population: </span>{i.population.toLocaleString()}</p>
                       <p><span>Region: </span>{i.region}</p>
                       <p><span>Sub Region: </span>{i.subregion}</p>
                       <p><span>Capital: </span>{i.capital}</p>
                       </CountryInfoDetailsInner>
                       <CountryInfoDetailsInner className="second">
                       <p><span>Top Level Domain: </span>{i.topLevelDomain}</p>
                       <p><span>Currencies: </span>{i.currencies[0].name}</p>
                       <p><span>Languages: </span>{i.languages.map(lang => lang.name).join(", ")}</p>
                       </CountryInfoDetailsInner>
                   </CountryInfoDetails>
                   <CountryBorders>
                       <p><span>Border Countries:</span></p>
                    {i.borders.map(border =>{
                      const borderName = getBorderCountryName(allCountries, border);
                      return (<Link to={`/country/${borderName}`}><button>{borderName}</button></Link>)
                    })}
                   </CountryBorders>
               </CountryInfo>
               </CountryDetailsWrapper>
           ))}
        </CountryDetailStyles>
  )
}

export default CountryDetail;

【问题讨论】:

  • 所以matchingCountry 这里const matchingCountry = allCountries.find 返回undefined
  • 我认为您的 fetchItem 函数存在问题

标签: javascript reactjs api axios frontend


【解决方案1】:

问题就在这里:

{item.map(i => (

您从 axios 调用中获得此响应并设置为以下状态:

const response = await axios.get(`https://restcountries.eu/rest/v2/name/${match.params.name}?fullText=true`);
    setItem(response.data)

在第一次渲染时item 没有任何数据,因为 axios 调用需要一些时间才能完成,当没有数据并且您尝试对其进行迭代时,它会抛出此类错误。所以试试这个:

{
  ( item && item.length > 0 )  // conditional rendering or such type of check is neede before iteration
  ?
  // Iterate here
  :
  null // do nothing
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 2022-01-14
    • 2022-06-22
    • 2015-10-16
    • 2021-12-28
    • 1970-01-01
    • 2021-08-16
    • 2020-10-11
    相关资源
    最近更新 更多