簡體   English   中英

無法使用 array.map() 將選項元素填充到 select 元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM