[英]Unable to populate option elements to select element using array.map()
我從 api 獲取了一系列車輛制造,並嘗試將 map 數組中的每個項目轉換為 select 元素中的選項元素:
const Makes = () => {
return (
<select aria-label="Select a make">
{/* Populate with option elements based on the years state and its index */}
<option value="">Select a make</option>
{makes.map((make) => <option key={make.toString()} value={make}>test</option>)}
</select>
);
};
make 在上面的makes
中定義為一個空數組,我用fetchMakesByYear
function 填充數組,如下所示:
const fetchMakesByYear = async () => {
const url = `https://www.fueleconomy.gov/ws/rest/vehicle/menu/make?year=${year}`;
const headers = {
headers: {
'Content-Type': 'application/xml',
Accept: 'application/xml',
},
};
try {
const data = await fetch(url, headers);
const itemUnformatted = await data.text();
const makesByYearUnformatted = convert.xml2js(itemUnformatted, { compact: true, spaces: 2 });
const makesByYear = makesByYearUnformatted.menuItems.menuItem;
for (let i = 0; i < makesByYear.length; i += 1) {
makes.push(makesByYear[i].text._text);
}
} catch (err) {
console.log(err);
}
};
useEffect(() => {
fetchMakesByYear();
});
不知道為什么沒有填充選項。 關於我在這里做錯了什么的任何想法? 謝謝。
使用makes
存儲 make 數組並在 fetch 上更新它,這將重新渲染您的組件並useEffect
在組件安裝時調用您的fetchMakesByYear
。
無限渲染是因為你沒有在useEffect
中傳遞依賴數組,所以它在每次渲染時都會調用它。
const [makes,setMakes] = useState([]) // use state to hold your array
const fetchMakesByYear = useCallback(async () => { // use useCallback hook to wrap your function so that this function is not created on every render and hence doesn't call useEffect as we will be giving it as a dependency
const url = `https://www.fueleconomy.gov/ws/rest/vehicle/menu/make?year=${year}`;
const headers = {
headers: {
'Content-Type': 'application/xml',
Accept: 'application/xml',
},
};
try {
const data = await fetch(url, headers);
const itemUnformatted = await data.text();
const makesByYearUnformatted = convert.xml2js(itemUnformatted, { compact: true, spaces: 2 });
const makesByYear = makesByYearUnformatted.menuItems.menuItem;
for (let i = 0; i < makesByYear.length; i += 1) {
makes.push(makesByYear[i].text._text);
}
setMakes(makes) // set state to update your array in the state
} catch (err) {
console.log(err);
}
},[]);
useEffect(()=>{
fetchMakesByYear()
},[fetchMakesByYear]) // add dependency in useEffect here
return (
{Makes()}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.