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

如何在从API获取数据后为react-select组件设置默认值

React-Select 异步接口数据设置选中值解决方案

存在的问题

  • 初始状态类型不匹配:useState初始化currency为数组格式,接口返回后存入的是对象格式,类型不一致会导致渲染异常
  • defaultValue不支持动态更新:react-select 的defaultValue仅在组件首次挂载时生效,异步请求接口返回数据时组件已经完成首次渲染,无法触发更新
  • Controller 属性遗漏:react-hook-form 的Controller需要同时绑定onChange和value才能实现值的双向同步,你只提取了onChange属性
  • 传值格式错误:当前使用的是单选Select,defaultValue传入了[currency]数组格式,单选场景需要传入对象格式,仅多选场景需要传入数组

修正代码

1. 调整状态初始化并从react-hook-form中导出setValue

// 初始值设为null,和后续存储的对象类型统一
const [currency, setCurrency] = useState(null);
// 从useForm中解构出setValue方法,用于同步更新表单字段值
const { control, setValue } = useForm();

2. 调整useEffect中的数据处理逻辑

useEffect(() => {
  if (sessionStorage.getItem('AccountId')) {
    axios.get(process.env.REACT_APP_SQL_API_URL + 'Organisation/' + query.search.split('=')[1])
      .then(res => {
        const curValue = res.data[0].currency;
        // 从选项中匹配对应对象,保证label和options配置一致
        const selectedCurrency = [
          { value: 'USD', label: 'USD $' }, 
          { value: 'TZS', label: 'TZS' }
        ].find(opt => opt.value === curValue);
        setCurrency(selectedCurrency);
        // 同步更新react-hook-form的表单字段值
        setValue('currency', selectedCurrency);
      })
      .catch(error => console.log(error.response))
  } else {
    history.push('/login')
  }
}, [])

3. 调整Select组件配置

<Controller
  rules={{ required: true }}
  name="currency"
  control={control}
  // 提取field中的value属性做绑定
  render={({ field: { onChange, value } }) =>
    <Select
      onChange={(e) => {
        onChange(e)
        // 如有需要可以同步更新自定义state:setCurrency(e)
      }}
      options={[{ value: 'USD', label: 'USD $' }, { value: 'TZS', label: 'TZS' }]}
      // 用value属性替代defaultValue,实现动态更新选中值
      value={value}
    />
  }
/>

内容的提问来源于stack exchange,提问作者Ibrahim Shabbir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:54:08