You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-select中按指定值设置默认值?代码无效求指导

问题出在defaultValue的逻辑写法上

你的defaultValue代码有两个明显错误:

  1. Array.find()的回调需要返回布尔值来筛选匹配项,但你现在直接返回了一个对象,导致find()根本找不到正确的条目
  2. 你把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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:18:21