簡體   English   中英

通過使用react-select映射對象數組來生成選項

[英]Generate options by mapping over array of objects with react-select

我正在使用react-select在我的create-react-app創建一個Select選項,並試圖映射到一組對象上以生成選項。 我的應用程序加載正常,但是當我單擊“選擇”時,出現以下錯誤: Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead. Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead.

我正在將數據通過props傳遞給組件,而props可以正常工作,並且數據的結構如下:

const guests = [
    {
        name: 'Kait',
        plus: true,
        plusName: 'Kitty'
    },
    {
        name: 'Séanin',
        plus: true,
        plusName: 'Guest'
    }
]

這是選擇組件:

<Select
   value={selectedOption}
   onChange={this.handleChange}
   options={
      this.props.guests.map((guest, index) => {
         return {
            label: guest,
            value: guest,
            key: index
         }
      })
   }
/>

關於如何解決此問題的任何想法?

您可能需要在渲染組件之前生成數組

const options = this.props.guests.map((guest, index) => {
     return {
        label: guest.name,
        value: guest,
        key: index
     }
})
<Select
   value={selectedOption}
   onChange={this.handleChange}
   options={options}
/>

編輯:

是因為您要在標簽字段中傳遞對象。 您應該改為傳遞一個字符串

發生錯誤是因為標簽設置為guest (對象)而不是guest.name (字符串)。

進行以下更改將起作用。

<Select
   value={selectedOption}
   onChange={this.handleChange}
   options={
      this.props.guests.map((guest, index) => {
         return {
-            label: guest,
+            label: guest.name
            value: guest,
            key: index
         }
      })
   }
/>

您可以在下面的沙盒鏈接中嘗試一下。
進行修改。answer.55173409

Sung M. Kim的答案是正確的,但是有一種更簡便的方法將屬性用作標簽和值,而無需重新映射選項數組。

使用道具getOptionLabelgetOptionValue可以保留對象映射。 兩者都接受一個函數,該函數將單個選項作為參數,並從適當的對象屬性作為字符串返回值或標簽。

<Select
    options={this.props.guests}
    getOptionLabel={(option) => option.name}
    { /* Couldn't find a value in your structure, so I used name again */ }
    getOptionValue=((option) => option.name}
    { ... }
/>

有關更多信息 ,請參見文檔

暫無
暫無

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

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