小编典典

React Select-如何显示/遍历api调用选项中的数据而不是硬编码选项?

reactjs

我正在使用react-
select,我不想对应该显示的选项进行硬编码,但是选项是我从api获取的数据。我真的找不到任何东西,而且我试图做的事情也没有用,因为什么也没显示出来。有谁知道?谢谢!!!

api.js:

export function availableCities() {
   return axios.get('/cities').then(function (response) {
      return response.data;
   })
}

零件:

import Select from 'react-select';
import {availableCities} from '../utils/api.js';

class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
     } 
   }
   componentDidMount() {
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            })
            console.log("hello", this.state.cities)
        })
   }

   handleChange(selectedOption) {
    this.setState({selectedOption});
   }
 render(){
    let options = this.state.cities.map(function (city) {
            return city.name;
    })
 return (
      <div>
           <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                options={options}                  
            />
      </div>
  )
 }
}

数据(this.state.cities是一个对象数组,看起来像:

{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}

...

阅读 232

收藏
2020-07-22

共1个答案

小编典典

这里的问题来自数组中的对象。react-select需要具有以下键的对象数组才能理解它:valuelabel

因此,在渲染中,您可以替换

let options = this.state.cities.map(function (city) {
  return city.name;
})

通过,例如

let options = this.state.cities.map(function (city) {
  return { value: city.countryCode, label: city.name };
})

或者,就像pritesh指出的那样,只需告诉react-select要使用什么键

render () {
  return (
    <div>
      <Select
        name="form-field-name"
        value={this.state.value}
        onChange={this.handleChange}
        clearable={this.state.clearable}
        searchable={this.state.searchable}
        labelKey='name'
        valueKey='countryCode'
        options={this.state.cities}                  
      />
    </div>
  )
}

希望这可以帮助你!

2020-07-22