简体   繁体   English

无法使用 array.map() 将选项元素填充到 select 元素

[英]Unable to populate option elements to select element using array.map()

I'm getting an array of vehicle makes from an api, and trying to map each item in the array to an option element within a select element:我从 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>
    );
  };

makes is defined in the upper scope as an empty array, and I'm filling the array with a fetchMakesByYear function that looks like this: 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();
  });

Not sure why the options are not being populated.不知道为什么没有填充选项。 Any ideas on what I'm doing wrong here?关于我在这里做错了什么的任何想法? Thanks.谢谢。

Use state to store the makes array and update it on fetch which will re render your component and useEffect to call your fetchMakesByYear on component mount.使用makes存储 make 数组并在 fetch 上更新它,这将重新渲染您的组件并useEffect在组件安装时调用您的fetchMakesByYear

Infinite render is because you have not passed dependency array in useEffect , so it calls it on every render.无限渲染是因为你没有在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