我想把所有国家都加入国家,但问题是国家只返回一个国家



大家好,我想把所有国家添加到州,但问题是州只返回一个国家的

const [country, getCountry] = useState([]); useEffect(() => {
axios
.request("https://restcountries.com/v3.1/all")
.then((response) => {
response.data.forEach((element) => {
getCountry(element.name.official);
});
})
.catch(function (error) {
console.error(error);
}); }, []);

您正在逐个设置,最后一个将是最终状态,因此您可以执行以下操作:

.then((response) => {
getCountry(response.data.map((element) => element.name.official))
})

首先,您需要将所有国家/地区存储在另一个数组中,然后您可以将该数组存储在您的状态中。你现在所做的是在每次迭代中用不同的国家更新你的州。这就是为什么你所在的州只有一个国家。我已经更新了对我有效的实现,但对于forEach,您应该查看map:Array.prototype.map((

const [country, setCountry] = useState([])
useEffect(() => {
axios
.request("https://restcountries.com/v3.1/all")
.then((response) => {
const countries = []
response.data.forEach((element) => {
countries.push(element.name.official);
});
setCountry(countries);
})
.catch(function (error) {
console.error(error);
}); 
}, []);

最新更新