通过使用react-select映射对象数组来生成选项

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

我正在使用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.

我通过道具将数据传递给组件,工作正常,数据结构如下:

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

这是Select组件:

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

关于如何解决这个问题的任何想法?

javascript reactjs create-react-app react-select
3个回答
0
投票

您可能必须在渲染组件之前生成数组

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

编辑:

是因为您在标签字段中传递了一个对象。你应该传递一个字符串


0
投票

发生错误是因为标签设置为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
         }
      })
   }
/>

您可以在下面的沙箱链接中试用它。 Edit so.answer.55173409


0
投票

Sung M. Kim‘s answer是正确的,但有一种更简单的方法可以将属性用作标签和值,而无需重新映射选项数组。

使用道具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}
    { ... }
/>

有关更多信息,请参阅documentation

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