ReactJS:自动填充从API调用中选择

问题描述 投票:1回答:1

我有这个API调用,返回的宠物小精灵类型如下:

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

这是一个函数的结果,该函数采用所有神奇宝贝的值并过滤出重复项等。使用相同的函数来获取这些值并填充选择选项:

  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选项值。请参见下图:

输出如下:

enter image description here

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

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>
    }

  })();
javascript reactjs ecmascript-6
1个回答
0
投票

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

map
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>将仅返回第一个元素。您可以将JSX元素推送到数组上并返回该数组,但这似乎仍然是很多间接的。

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

© www.soinside.com 2019 - 2024. All rights reserved.