繁体   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