簡體   English   中英

從 React 中的數組填充選擇選項

[英]Populate select options from an array in React

我有這個 API 調用,它返回 Pokemon 的類型,如下所示:

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

這是一個函數的結果,該函數獲取所有 Pokemon 值並過濾掉重復項等。 相同的函數用於獲取這些值並填充選擇選項:

  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 選項值。 請看下圖:

輸出如下:

在此處輸入圖片說明

此外,當我之前執行 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>
    }
    
  })();

<option>標簽應該放在每個元素周圍,而不是全部。 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>

對於第二個例子中, return在循環內將只返回第一個元素。 您可以將 JSX 元素推送到一個數組上並返回它,但這似乎仍然有很多間接性。

在這兩個示例中,使用reduce將數組中的每個元素擴展到數組累加器是一種反模式; map在這方面做得最好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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