我的 API 回傳低于輸出。
[
"ANT",
"ARG",
"ARM",
"BUR",
"UAE"
]
在我的陣列中,我需要存盤countryname對應于這些countrycode. 所以為此我country-data在react. 所以我可以得到輸出,就像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。
Edit1:-
alert(countries[res.data[0]].name);//這條線正在作業。
但const _countryData = res.data.map((code) => countries[code].name); 給出錯誤。

uj5u.com熱心網友回復:
直接改變狀態值不符合 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" },
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416671.html
標籤:
