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

无法从JSON对象填充React Select下拉菜单问题求助

解决react-select下拉菜单填充报错问题

问题原因

react-select组件的options属性要求传入数组类型的数据,且数组内的每个元素必须包含value和label字段(两个字段的值可以一致)。你当前传入的是一个键值对对象{0: 'John', 1: 'Davis', 2: 'Sherry'},对象本身没有map方法,因此触发了props.options.map is not a function的错误。

解决方案

将返回的对象转换为符合react-select要求的数组格式,可通过Object.entries()遍历对象的键值对,再映射成包含value和label的对象数组。

修改后的完整代码如下:

import React, { useState, useEffect } from 'react'
import Select from 'react-select';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("/listEmployees")
      .then((response) => response.json())
      .then((data) => {
        const empObj = JSON.parse(data.empPartition);
        // 将对象转换为react-select需要的数组格式
        const empOptions = Object.entries(empObj).map(([key, name]) => ({
          value: name,
          label: name
        }));
        setData(empOptions);
        console.log(empOptions);
      });
  }, []);

  return (
    <div>
       <Select options={data} />
    </div>
  )
}

export default App;

关键说明

  • Object.entries(empObj)会把目标对象转换成键值对数组,示例输出为[['0', 'John'], ['1', 'Davis'], ['2', 'Sherry']]
  • 通过map方法将每个键值对转换为{value: 姓名, label: 姓名}的结构,完全匹配react-select的options格式要求

内容的提问来源于stack exchange,提问作者Shivayan Mukherjee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:38:15