我有一個國家代碼陣列,我需要有名字。我試圖從州(axios 呼叫)訪問國家資料,然后按國家代碼過濾,然后從新陣列中提取國家的通用名稱。(我正在使用 restcountries.com api)。
- 如果我創建一個新的狀態來映射,我會得到太多的重新渲染。-現在,雖然邊界國家資訊在那里,但我無法訪問它,我收到“無法讀取未定義的屬性”錯誤,這通常與生命周期問題有關,因此我使用了何時訪問的條件資訊。我仍然無法使其穩定并回傳我需要的名稱。有人可以看看并告訴我我做錯了什么嗎?提前致謝
import axios from "axios";
const BorderCountries = (props) => {
const [countriesList, setCountriesList] = useState([]);
useEffect(() => {
axios
.get(`https://restcountries.com/v3.1/all`)
.then((countries) => setCountriesList(countries.data))
.catch((error) => console.log(`${error}`));
}, []);
const getCountryName = () => {
const codes = props.data;
const borderCountries = [];
codes.map((code) => {
const borderCountry = countriesList.filter((country) =>
country.cca3.includes(code)
);
borderCountries.push(borderCountry);
});
// console.log(borderCountries);
if (props.data.length === borderCountries.length) {
const borderName = borderCountries.map((border) =>
console.log(border[0].name.common)
);
return borderName
}
};
return (
<div>
<h3>Border Countries:</h3>
{getCountryName()}
</div>
);
};
export default BorderCountries;
uj5u.com熱心網友回復:
const getCountryName = () => {
const codes = props.data;
if(countriesList.length === 0) return <></>;
const borderCountries = [];
codes.map((code) => {
const borderCountry = countriesList.filter((country) =>
country.cca3.includes(code)
);
borderCountries.push(borderCountry);
});
// console.log(borderCountries);
if (props.data.length === borderCountries.length) {
const borderName = borderCountries.map((border) =>
console.log(border[0].name.common)
);
return borderName
}
};
試試這個,你忘了等待通話結束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370892.html
上一篇:ReactAntDesignform.resetFields()不呼叫<Form.Items>的onChange事件
下一篇:ReactHookuseEffect缺少依賴項:'ans.group._id'。要么包括它要么洗掉依賴陣列,為什么?
