如何在react-select中按指定值设置默认值?代码无效求指导
问题出在
defaultValue的逻辑写法上 你的defaultValue代码有两个明显错误:
Array.find()的回调需要返回布尔值来筛选匹配项,但你现在直接返回了一个对象,导致find()根本找不到正确的条目- 你把
x.id === mainparentId的布尔结果存成了c,还试图访问c.id和c.categoryName——布尔值根本没有这些属性,这会导致返回无效对象或者报错
修正后的代码
直接调整defaultValue的逻辑,先找到匹配的原始数据,再转成react-select需要的结构:
<Select options={getMainCategory.data.map((item) => { return { value: item.id, label: item.categoryName }; })} defaultValue={() => { // 先找到id匹配的项 const matchedItem = getMainCategory.data.find(x => x.id === mainparentId); // 存在的话转成select需要的格式,不存在就返回null return matchedItem ? { value: matchedItem.id, label: matchedItem.categoryName } : null; }} onChange={onOptionChange} />
更简洁的写法(可选)
如果数据结构稳定,也可以用可选链简化:
<Select options={getMainCategory.data.map(item => ({ value: item.id, label: item.categoryName }))} defaultValue={getMainCategory.data .find(x => x.id === mainparentId) ?.((item) => ({ value: item.id, label: item.categoryName }))} onChange={onOptionChange} />
额外提醒
- 要保证
mainparentId和item.id的类型完全一致,比如都是数字或者都是字符串,不然会匹配失败 - 如果
getMainCategory.data是异步加载的,初始渲染时数据为空,defaultValue会是null,建议等数据加载完成后再渲染Select组件
内容的提问来源于stack exchange,提问作者RoyalDesigner
相关产品推荐
相关产品推荐

