在 React 中从 API 填充动态下拉列表的步骤

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

我正在尝试根据 API 响应中返回的数据构建一个下拉列表。 API 响应如下所示:

{"departments": ["Admin","HR","IT","OPS","Accounts"]}

检索就是这样。我需要帮助以下拉列表的形式访问数据

<div>


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

function Dropdown() {

  const [data, setData] = useState([{}])

  useEffect(() => {
    fetch("/listDepartments").then(
      response => response.json()
    ).then(
      data => {
        setData(data)
        console.log(data)
      }
    )
  }, [])

  return (
    <div>
     <Select options={data.departments} />
    </div>
  )
}
export default Dropdown;

错误 无法使用“in”运算符在管理中搜索“选项” 类型错误:无法使用“in”运算符在管理中搜索“选项”

javascript reactjs
1个回答
0
投票

试试这个:

function Dropdown() {

    // here, just default it to `[]`
    const [data, setData] = useState([])
  
    useEffect(() => {
      fetch("/listDepartments").then(
        response => response.json()
      ).then(
          data => {
              // put the departments data in the state
          setData(data.departments)
          console.log(data.departments)
        }
      )
    }, [])
  
    return (
      <div>
        {/* now you can map like this */}
        {data.map(e => (
          <div key={3}>{e}</div>
       ))}
      </div>
    )
  }
  export default Dropdown;
© www.soinside.com 2019 - 2024. All rights reserved.