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

如何在react-native-select-dropdown中动态加载带id的API下拉列表数据?

实现方案

1. 定义状态存储动态数据

使用React状态存储接口返回的下拉选项数据集,也可以额外定义状态存储选中项方便后续业务使用:

import { useState, useEffect } from 'react';
import SelectDropdown from 'react-native-select-dropdown';

// 组件内部代码
const [countries, setCountries] = useState([]);
// 可选:存储选中的国家对象,方便其他业务逻辑调用
const [selectedCountry, setSelectedCountry] = useState(null);

2. 调用API动态加载数据

在useEffect中发起接口请求,拿到返回数据后更新到状态中:

useEffect(() => {
  const fetchCountryList = async () => {
    try {
      // 替换为你的实际业务接口地址,也可根据需求换成axios等请求库
      const response = await fetch('https://你的接口地址');
      const result = await response.json();
      // 接口返回的对象数组直接赋值给状态即可
      setCountries(result);
    } catch (error) {
      console.error('国家列表加载失败:', error);
    }
  };

  fetchCountryList();
}, []);

3. 调整SelectDropdown组件配置适配对象数组

因为当前data传入的是对象数组,需要修改文本展示的回调逻辑,同时可以在选中回调中直接拿到完整对象获取id和名称:

注意:你给出的接口返回字段为namd,如果是拼写错误实际为name,自行替换对应字段即可。

<SelectDropdown
  data={countries}
  defaultButtonText={"请选择"}
  onSelect={(selectedItem, index) => {
    // 直接从选中项中获取名称和id
    console.log('选中名称:', selectedItem.namd);
    console.log('选中id:', selectedItem.id);
    // 可存储到状态中供后续使用
    setSelectedCountry(selectedItem);
  }}
  buttonTextAfterSelection={(selectedItem, index) => {
    // 选中后按钮上展示的文本
    return selectedItem.namd;
  }}
  rowTextForSelection={(item, index) => {
    // 下拉选项每行展示的文本
    return item.namd;
  }}
/>

补充说明

  • 如果需要设置默认选中值,可以在接口数据加载完成后,通过defaultValue传入匹配的完整对象,或者用defaultValueByIndex指定对应下标
  • 数据加载过程中可以加loading状态优化体验,比如数据为空时按钮展示“加载中”

内容的提问来源于stack exchange,提问作者Juhi Kukreja

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:42:00