[英]Copying data of one array with transformation into another array in javascript/react
我的 API 在 output 以下返回。
[
"ANT",
"ARG",
"ARM",
"BUR",
"UAE"
]
在我的數組中,我需要存儲與這些countrycode
對應的countryname
。 所以為此我在react
中使用了country-data
。 所以我可以得到 output 像console.log(countries["UAE"].name);
我需要將國家名稱存儲在下面聲明的countryData
數組中。
我的反應代碼是。
this.state = {
countryData: [],
};
我正在使用如下數組代碼。
updateDropdownData() {
axios.get(`http://localhost:8080/country_code`).then((res) => {
res.data.map((code) => {
alert(countries[code].name);
countryData.push.apply(countryData, countries[code].name);
});
this.setState({ countryData });
});
}
但我收到錯誤
index.bundle.js:122 Uncaught (in promise) ReferenceError: countryData is not defined
at index.bundle.js:122:217123
at Array.map (<anonymous>)
我在做什么錯誤。 我是javascript
的新手並react
。
編輯1:- alert(countries[res.data[0]].name);
//這條線正在工作。
但是const _countryData = res.data.map((code) => countries[code].name);
給出錯誤。
直接更改 state 值不適合 React 的方法。
updateDropdownData() {
axios.get(`http://localhost:8080/country_code`).then((res) => {
const _countryData = res.data.map((code) => countries[code].name )
this.setState({ countryData: _countryData });
});
}
countries
變量必須在您運行它的位置。 變量的形狀應如下所示。
const countries = {
"ANT" : { name : "ant_name" },
"ARG" : { name : "arg_name" },
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.