2 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
查看調(diào)用 API 的結(jié)果,是這樣的形式:
[
{"Country":"Micronesia, Federated States of","Slug":"micronesia","ISO2":"FM"},
{"Country":"Bangladesh","Slug":"bangladesh","ISO2":"BD"},
{"Country":"Bouvet Island","Slug":"bouvet-island","ISO2":"BV"},
// ...and so on...
]
所以Country不是數(shù)組,它是數(shù)組中每個(gè)對象的屬性。
如果您的目標(biāo)是Country從每個(gè)對象中提取屬性,請獲取數(shù)組,然后使用map提取該屬性,也許使用解構(gòu):
const data = await axios.get(countriesURL);
return data.map(({Country}) => Country);

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
重組在這里沒有得到妥善處理。
const { data: [ x ] } = {data: [{"Country":"Micronesia, Federated States of","Slug":"micronesia","ISO2":"FM"},{"Country":"Bangladesh","Slug":"bangladesh","ISO2":"BD"}]}
這里x將{"Country":"Micronesia, Federated States of","Slug":"micronesia","ISO2":"FM"}
下一個(gè):
const {Country} = x
國家將在這里"Micronesia, Federated States of"
and"Micronesia, Federated States of"是一個(gè)字符串,它沒有map函數(shù)。
{ data: [ {Country} ] }訪問所有密鑰的錯(cuò)誤方法也是如此。
const fetchCountries = async () => {
try {
const countries = await axios
.get(countriesURL)
.then((x) => x.data);
return countries.map(({ Country }) => Country);
} catch (error) {
console.log(error);
return []
}
};
const fetchCountries = async () => {
try {
const countries = await axios
.get("https://api.covid19api.com/countries")
.then((x) => x.data);
return countries.map(({ Country }) => Country).sort();
} catch (error) {
console.log(error);
return []
}
};
fetchCountries().then(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
獲取其他信息:
// const axios = require("axios"); // for node js
const fetchCountriesInfoParallel = async (countries = []) => {
const promises = countries.map((country) =>
axios
.get(`https://api.covid19api.com/live/country/${country}`)
.then(({ data }) => data)
);
try {
return await Promise.all(promises);
} catch (error) {
console.log(error);
return [];
}
};
fetchCountriesInfoParallel(["Afghanistan", "Albania", "Algeria"]).then(
console.log
);
const fetchCountriesInfoSeries = async (countries = []) => {
let results = [];
for (let index = 0; index < countries.length; index++) {
const country = countries[index];
const data = await axios
.get(`https://api.covid19api.com/live/country/${country}`)
.then(({ data }) => data);
results.push(data);
}
return results;
};
fetchCountriesInfoSeries(["Afghanistan", "Albania", "Algeria"]).then(
console.log
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
添加回答
舉報(bào)