使用react-select遇React唯一key prop警告,求下拉列表key设置方法
解决react-select的"Each child in a list should have a unique 'key' prop"警告
问题描述
使用react-select组件时收到React警告:
Warning: Each child in a list should have a unique "key" prop.
组件代码如下:
import React from "react"; import Select from "react-select"; import styles from "./Filter.module.scss"; interface SearchBarProps { setParametr: React.Dispatch<React.SetStateAction<string>>; data: Array<{ name: string; value: number }>; placeholder: string; } export const SearchBar: React.FC<SearchBarProps> = (props) => { // const [options, setOptions] = React.useState([]); const changeValue = (event: { name: string; value: number } | null) => { props.setParametr(event?.name || ""); }; return ( <Select className={styles.input} placeholder={props.placeholder} onChange={(event) => changeValue(event)} getOptionLabel={(option) => { return option.name; }} getOptionValue={(option) => { return option.value.toString(); }} options={props.data} /> ); };
解决方法
react-select内部会用getOptionValue返回的值作为下拉列表项的key,问题根源在于生成的key不唯一或组件版本问题,按以下步骤处理:
检查数据源唯一性:确认传入的
props.data中,每个item的value字段是唯一数值。如果存在重复value,会导致生成的key重复,触发警告。更换key生成字段:如果
value无法保证唯一,可改用唯一的name字段(需确保name无重复)生成key:
getOptionValue={(option) => { return option.name; }}
或者给数据源添加唯一id字段(比如后端返回的唯一标识),用id生成key:
// 修改props.data的结构 interface SearchBarProps { // ...其他属性 data: Array<{ id: string; name: string; value: number }>; } // 更新getOptionValue getOptionValue={(option) => { return option.id; }}
- 升级react-select版本:若使用的是较旧版本,可能存在内部列表key处理的bug,尝试升级到最新稳定版。
内容的提问来源于stack exchange,提问作者Denis Dryagin
相关产品推荐
相关产品推荐

