从 api 中获取的项目未显示在下拉列表中 react-select

Items fetched from api not shown in dropdown react-select

使用 React 应用程序并尝试在下拉菜单中显示选项,例如功能,我正在使用 react-select<Select> 标签。api 抓取一切正常,数据可用.但是,它在下拉菜单中没有显示任何选项。

import React, { Component } from 'react';
import Select from 'react-select';
import url from '../services/urlService';

class TechCompanies extends Component {

    state = {
        values: []
    }

    componentDidMount() {
        fetch(url + 'api/roles/roles')
            .then(res => res.json())
            .then(res => this.setState({
                values: res.Data
            }))
            .catch(error => console.log(error))
    }

    render() {
        return (
            <div>
                <Select>
                    {this.state.values.map((role) => {
                        return <option key={role.RoleId} value={role.RoleId}
                        >{role.RoleName}</option>
                    })}
                </Select>
            </div>
        )
    }
}

export default TechCompanies;

这对我有用。您只需将数组作为道具 options 传递给 Select 组件。您还可以将 onChange 处理程序作为 prop 以及当前选择的值传递。

render() {
    return (
      <div>
        <Select
        options={this.state.values}>
        </Select>
      </div>
    )
  }

你可以在他们的 npm 页面上找到更多相关信息 https://www.npmjs.com/package/react-select

react-select 需要 options 属性。

您可以使用 this.state.values

创建 option 数组
    let option = []
    if (this.state.values.length > 0) {
      this.state.values.forEach(role => {
        let roleDate = {}
        roleDate.value = role.RoleId
        roleDate.label = role.RoleName
        option.push(roleDate)
      })
    }

用法

<Select options={options} />

注意:: 还要确保您从 API 调用中得到响应,为了获得有保证的响应,您必须使用 async-await 来获取数据。

Demo