使用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。当这种情况发生时,没有其他数据通过。有没有一种方法可以捕捉到这一点,这样如果该值未定义,我仍然可以获得所有剩余的数据?

我建议在照片阵列的映射中检查未定义的值

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

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

相关内容

最新更新