json - 使用 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;
}),
代替空字符串,您还可以替换默认图像
推荐阅读
- linux - 本地主机无法分配请求的地址
- dotnetnuke - 如何在 Dotnet Nuke 中添加 aria 标签以扩展最小化图标代码?
- mysql - MySQL - 为什么我的查询只返回一行而不是三行?
- python - Mailchimp API 无效服务器
- api - 来自 localhost 上 API / vue.js 的动态图像路径
- azure - 与管理组共享 Azure 共享映像库
- react-native - 从 date.fns 库中获取时区列表
- windows - 系统服务无法上网
- flutter - Appbar底部内的Flutter标签栏给出底部溢出异常
- mongodb - 带有条件的MongoDB聚合查找