从React中的数组中填充选择选项 [英] Populate select options from an array in React

查看:47
本文介绍了从React中的数组中填充选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个API调用,返回的神奇宝贝类型如下:

I have this API call that returns types of Pokemon as in:

["Grass", "Poison", "Fire", "Flying", "Water", "Bug", "Normal", "Electric", "Ground", "Fighting", "Psychic", "Rock", "Ice", "Ghost", "Dragon"]

这是一个函数的结果,该函数获取所有Pokemon值并过滤出重复项等.相同的函数用于获取这些值并填充选择选项:

This is a result of a function that takes all Pokemon values and filters out duplicates and such. The same function is used to take these values and populate the select options:

  let pokemonSingleType = (() => {
    let types = pokemonData.reduce((acc, { type }) => (acc.push(...type), acc), [])
    types = new Set(types);
    types = [...types];
    console.log(types);
    return <option>
      {types}
    </option>
  })();

在下面显示:

 <select value={searchType} onChange={updateSearchByType.bind(this)} 
  className="formcontrol" id="typeSelect">
  {pokemonSingleType}
</select>

问题是我将整个数组作为一个Select选项值.请参见下图:

The issue is that I get the whole array as one Select option value. Please see image below:

输出如下:

此外,当我之前执行for循环时,它会在第一次迭代时停止:

Also, when I do a for loop before, it stops at the first iteration:

let pokemonSingleType = (() => {
    let types = pokemonData.reduce((acc, { type }) => (acc.push(...type), acc), [])
    types = new Set(types);
    types = [...types];
    for(let i =0; i< types.length; i++){
      return <option>
      {types[i]}
    </option>
    }
    
  })();

推荐答案

< option> 标签应放置在每个元素周围,而不是全部放置. map 是完成此操作的最直接方法:

<option> tags should be placed around each element, not all of them. map is the most direct way to accomplish this:

const Dropdown = ({options}) =>
  <select>
    {options.map((e, i) => <option key={i}>{e}</option>)}
  </select>
;

const pokemon = ["Grass", "Poison", "Fire", "Flying", "Water", "Bug", "Normal", "Electric", "Ground", "Fighting", "Psychic", "Rock", "Ice", "Ghost", "Dragon"];
ReactDOM.render(<Dropdown options={pokemon} />, document.body);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

对于第二个示例,循环内的 return 将仅返回第一个元素.您可以将JSX元素推到数组上并返回它,但这似乎仍然是很多间接的.

For the second example, return inside the loop will only return the first element. You could push the JSX elements onto an array and return that, but this still seems like a lot of indirection.

在两个示例中,使用 reduce 将数组中的每个元素散布到数组累加器上都是一种反模式; map 做到最好.

In both examples, using reduce to spread each element in an array onto an array accumulator is an antipattern; map does this best.

这篇关于从React中的数组中填充选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆