我有这个Dropdown菜单实例:
<Dropdown
selection
options={this.state.options}
search
value={value}
onChange={this.handleChange}
onSearchChange={this.handleSearchChange}
/>
当我的后端返回响应时,然后将其设置为状态,结构如下:
"options": [
{
"text": "New York,All Airports (NYC) , USA",
"value": "NYC"
},
{
"text": "New York,Newark Liberty Intl (EWR), USA",
"value": "EWR"
},
{
"text": "New York,John F Kennedy (JFK), USA",
"value": "JFK"
},
{
"text": "New York,La Guardia (LGA), USA",
"value": "LGA"
}
]
......我收到了这个警告:
警告:flattenChildren(...):遇到两个孩子一样 键,
1:$BLZ
。子键必须是唯一的;当两个孩子分享一个 键,只会使用第一个孩子。
in select (created by Dropdown)
in div (created by Dropdown)
in Dropdown (created by SearchForm)
如何为这些元素添加密钥以防止出现此警告?
答案 0 :(得分:2)
因此,查看Semantic UI source for the dropdown组件的代码,render options函数将传入的选项转换为DropdownItem组件数组:
renderOptions = () => {
const { multiple, search, noResultsMessage } = this.props
const { selectedIndex, value } = this.state
const options = this.getMenuOptions()
if (noResultsMessage !== null && search && _.isEmpty(options)) {
return <div className='message'>{noResultsMessage}</div>
}
const isActive = multiple
? optValue => _.includes(value, optValue)
: optValue => optValue === value
return _.map(options, (opt, i) => (
<DropdownItem
key={`${opt.value}-${i}`}
active={isActive(opt.value)}
onClick={this.handleItemClick}
selected={selectedIndex === i}
{...opt}
// Needed for handling click events on disabled items
style={{ ...opt.style, pointerEvents: 'all' }}
/>
))
}
通过获取值prop并将索引附加到它来设置此数组的键:
key={`${opt.value}-${i}`}
由于使用了索引,因此应始终是唯一的,但hidden inputs的代码的另一部分
renderHiddenInput = () => {
debug('renderHiddenInput()')
const { value } = this.state
const { multiple, name, options, selection } = this.props
debug(`name: ${name}`)
debug(`selection: ${selection}`)
debug(`value: ${value}`)
if (!selection) return null
// a dropdown without an active item will have an empty string value
return (
<select type='hidden' aria-hidden='true' name={name} value={value} multiple={multiple}>
<option value='' />
{_.map(options, option => (
<option key={option.value} value={option.value}>{option.text}</option>
))}
</select>
)
}
在这一个中,键仅设置为值,而不是值加索引。
<option key={option.value} value={option.value}>{option.text}</option>
这可能是您的问题,如果您有重复的值,那么密钥将不是唯一的。仔细检查选项列表,确保没有重复值。