无法从 Json 对象填充 React Select 下拉列表

问题描述 投票:0回答:1

我面临着从 JSON 对象填充反应选择下拉列表的问题,将下面的代码作为参考。任何帮助将不胜感激。

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) => {
        // put the employees data in the state
        setData(JSON.parse(data.empPartition));
        console.log(JSON.parse(data.empPartition));
      });
  }, []);

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

export default App;

控制台上的 JSON 对象如下所示

{0: 'John', 1: 'Davis', 2: 'Sherry'}
0: "John"
1: "Davis"
2: "Sherry"

下拉菜单显示在页面上,但不起作用并出现以下错误 props.options.map 不是一个函数 类型错误:props.options.map 不是函数 在 buildCategorizedOptions

reactjs json react-select
1个回答
0
投票

因此,将您的

data
形状视为;

{0: 'John', 1: 'Davis', 2: 'Sherry'}

react-select
接受的值options

{ label: string, value: string }[]

你必须首先将你的

data
转换为反应选择理解的
options
对象;

const input = { 0: 'John', 1: 'Davis', 2: 'Sherry' };

const transformed = Object.entries(input).map(([key, value]) => ({
  label: value,
  value: value
}));

console.log(transformed);

然后您可以将

transformed
值设置为
data
状态,并将其通过
option
属性传递给您的 Select 组件。

© www.soinside.com 2019 - 2024. All rights reserved.