首页 > 解决方案 > 带有 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''

我正在调试功能,我在日志中看到返回之前..设置了正确的值...

我不知道它最终是如何定义的。

标签: reactjsaxios

解决方案


你没有返回任何东西getCityId,因此错误undefined

改变这个:

axios.get(myUrl).then((res) => {

到 :

return axios.get(myUrl).then((res) => { // <-- add return before axios

然后试试这个:

getCityId(newCity).then((response) => console.log(response));

推荐阅读