reactjs - 带有 API 调用的函数
问题描述
我有一个功能:
const getCityId = (myCity) => {
try {
// set the url
const myUrl = `https://................com/tabs/categories.json?orderBy="title"&equalTo="${myCity}"`;
axios.get(myUrl).then((res) => {
//console.log(res.data);
const myData = res.data;
for (var key1 in myData) {
for (var key2 in myData[key1]) {
var myCityId = myData[key1].id;
}
}
console.log('display....' + myCityId);
return myCityId;
});
} catch (err) {
console.log(err);
return false;
}
};
比我这样做时的代码:
newCityId = getCityId(newCity);
我得到价值'未定义'
如果我尝试:
getCityId(newCity).then((response) => console.log(response));
我得到错误'无法读取未定义的属性'then''
我正在调试功能,我在日志中看到返回之前..设置了正确的值...
我不知道它最终是如何定义的。
解决方案
你没有返回任何东西getCityId
,因此错误undefined
改变这个:
axios.get(myUrl).then((res) => {
到 :
return axios.get(myUrl).then((res) => { // <-- add return before axios
然后试试这个:
getCityId(newCity).then((response) => console.log(response));
推荐阅读
- java - 同步的锁定对象是错误的吗?
- c++ - 为什么我在这里得到错误的总和?
- java - 系统错误:java.nio.file.InvalidPathException:
- java - Java程序将字符串作为用户输入并将其存储在数组中,然后打印它
- keycloak - Keycloak:如何在用户注册时向管理员发送电子邮件/如何创建自定义执行以发送电子邮件
- android - 恢复活动后,回收站视图显示空白屏幕
- node.js - Cheerio 如何获得与其他标签同级的文本节点
- oracle - 想要在贷方列显示计算的负余额,在借方列显示正数
- reactjs - 如何将 Paddle 与 NextJS 集成
- macos - 当我在 xcode 中添加 libcurl.4.tbd 作为依赖项时,实际会发生什么?