我正在使用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
}
})
}
/>
关于如何解决这个问题的任何想法?
您可能必须在渲染组件之前生成数组
const options = this.props.guests.map((guest, index) => {
return {
label: guest.name,
value: guest,
key: index
}
})
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
编辑:
是因为您在标签字段中传递了一个对象。你应该传递一个字符串
Sung M. Kim‘s answer是正确的,但有一种更简单的方法可以将属性用作标签和值,而无需重新映射选项数组。
使用道具getOptionLabel
和getOptionValue
你可以保持你的对象映射。两者都接受一个函数,该函数将单个选项作为参数,并将相应的对象属性中的值或标签作为字符串返回。
<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。