javascript - 相同的 API 请求,一个得到响应并存储它,另一个没有
问题描述
所以我有两个来自不同 API 的获取请求。我不明白为什么这个:
let [responseObj, setResponseObj] = useState({});
fetch(`https://community-open-weather-map.p.rapidapi.com/weather?units=${unit}&q=${uriEncodedCity}`, {
"method": "GET",
"headers": {
"x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
"x-rapidapi-key": process.env.REACT_APP_API_KEY
}
})
.then(response => response.json())
.then(response => {
if (response.cod !== 200) {
throw new Error()
}
setResponseObj(response);
setLoading(false);
})
.catch(err => {
setError(true);
setLoading(false);
console.log(err.message);
});
获取并存储响应,但这个没有:
let [geoObj, setGeoObj] = useState({});
fetch(`http://api.openweathermap.org/geo/1.0/direct?q=${uriEncodedCity}&limit=1&appid=${Key}`, {
"method": "GET"
})
.then(response => response.json())
.then(response => {
if (response.cod !== 200) {
throw new Error()
}
setGeoObj(response);
console.log(response);
})
.catch(err => {
setError(true);
setLoading(false);
console.log(err.message);
});
在第二个请求中,api 密钥有效,在网络选项卡中,我从 API 获取 json,但是当我尝试将其存储在响应中并将其记录到控制台时,它显示为空白,而在第一个请求中,我得到了 json 响应.
解决方案
我认为这是因为其中一个是一个数组,而您正试图将它存储在一个对象中——看看useState({})
.
我在codeandbox中尝试了这段代码,它工作正常。
推荐阅读
- java - 在 Java 中解密和重新验证 JWT 令牌
- php - 在 laravel 中使用碳的 settimezone 查询问题
- c# - C# Dapper 与泛型方法的一对多关系
- r - R mutate & gsub 其中模式基于列
- ruby-on-rails - Rails 创建唯一令牌
- android - 如何开始为华为开发移动应用程序
- qliksense - 在 SQL 语句之间的 loadscript 中连接
- vue.js - 从 API 获取 asyncData 时 Nuxt val.replace 不是函数
- jenkins - 用很长的清单杀死/停止詹金斯的工作
- sql - 在最后一个数据点之后的列的下一行中添加 0