首页 > 解决方案 > 使用 Fetch 有时会出现类型错误,因为照片的 href 未定义

问题描述

我正在建立一个房地产网站并从我正在做的 api 中获取信息

fetch(
        `https://realtor.p.rapidapi.com/properties/detail?listing_id=${ids.listId}&prop_status=${ids.propStatus}&property_id=${ids.propId}`,
        {
          method: "GET",
          headers: {
            "x-rapidapi-host": "realtor.p.rapidapi.com",
            "x-rapidapi-key":
              "xxxxxxxxxx"
          }
        }
      )
        .then(response => {
          const json = response.json();
          return json;
        })
        .then(json =>
          setDetails({
            photos: json.listing.photos.map(photo => photo.href),
            propertyType: json.listing.raw_prop_type,
            price: json.listing.price,
            beds: json.listing.beds,
            baths: json.listing.baths,
            sqrft: json.listing.sqft,
            yearBuilt: json.listing.year_built,
            listingAgent: json.listing.agent.name,
            email: json.listing.agent.email,
            photoCentered: json.listing.agent.photo.href,
            description: json.listing.description,
            loanAmount: json.listing.mortgage.estimate.loan_amount,
            rate: json.listing.mortgage.estimate.rate,
            term: json.listing.mortgage.estimate.term,
            monthlyPayment: json.listing.mortgage.estimate.monthly_payment,
            principle_interest:
              json.listing.mortgage.estimate.principle_and_interest,
            monthPropertyTax:
              json.listing.mortgage.estimate.monthly_property_taxes,
            monthlyHomeInsurance:
              json.listing.mortgage.estimate.monthly_home_insurance,
            totalPayment: json.listing.mortgage.estimate.total_payment,
            downPayment: json.listing.mortgage.estimate.down_payment,
            listingDateValue:
              json.listing.client_display_text.listing_date_value,
            addressNeighborhood:
              json.listing.client_display_text.address_with_neighborhood,
            propertyDisplayName:
              json.listing.client_display_text.prop_type_display_name
          })
        )
        .catch(err => {
          console.log(err);
        });

问题是有时房地产经纪人的照片有一个未定义的href。当这种情况发生时,其他数据都不会通过。有没有办法捕捉到这一点,如果该值未定义,我仍然可以获得所有其余数据?

标签: jsonreactjspromisefetchfetch-api

解决方案


我建议在您的照片数组映射中检查未定义的值

photos: json.listing.photos.map(photo =>{
   if(typeof photo.href === 'undefined'){
      return '';
   }
   return photo.href;
}),

代替空字符串,您还可以替换默认图像


推荐阅读