reactjs - 如何将带有“throw”的 if 条件放入 fetch...then API
问题描述
我需要在 fetch - .then 函数中放置一个带有 throw 的 if 条件,以检查响应数据是否正确,但我不知道该怎么做。
getWeather = (latitude, longitude) => {
const API_KEY = "";
const api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
fetch(api)
.then(response => response.json())
.then(data => {
this.setState({
locationName: data.name,
temperature: data.main.temp,
weatherDescription: data.weather[0].description,
isLoading: false,
})
})
};
解决方案
像这样:
fetch(api)
.then(response => response.json())
.then(data => {
if(**YOUR_CONDITION_HERE**){
this.setState({
locationName: data.name,
temperature: data.main.temp,
weatherDescription: data.weather[0].description,
isLoading: false,
} else {
throw new Error("data invalid");
}).catch(err => console.log(err));
推荐阅读
- google-directions-api - Directions API - 有中途停留的目的地
- r - 如何使用 R 读取文件夹中的所有 hdf 文件?
- asp.net-mvc - 根据第一个 Droplist 的值填充第二个 Droplist
- java - 延迟的 Springboot 事件发布者
- android - 如何以编程方式在 Android Q 中打开设置面板?
- java - java中的oracle查询性能
- javascript - 不允许在 JavaScript 中的 eyeIcon 上显示保存的密码
- java - Selenium 3.141.59 在 Eclipse 上不能与 JDK 12.0.2 一起使用
- python - python - 如何提取 DOCX 超链接的文本?
- logstash - logstash 自定义模式没有得到解决