首页 > 解决方案 > 如何在反应选择中制作api

问题描述

这是我的代码

我的状态

this.state = {
    loading: true,
    weather: [],
    cityName: [],
    selectedOption: '',

}

我的通话API

const getAPIcityName = Axios.get('http://dataservice.accuweather.com/locations/v1/topcities/100?').then((res) => {
        console.log('res' + res);
        this.setState({ cityName: res.AdministrativeArea.LocalizedName });
    }, (error) => {
        console.log('error', error)
    });
}

在这里我不会做选择城市的名字

handleChange(selectedOption) {
    this.setState({ selectedOption });
    console.log(selectedOption);
}

render() {
    let options = this.state.cityName.map((cityName) => {
        return cityName.AdministrativeArea.LocalizedName;
    })

    return (
        <div class="container">

            <h1 for="Search">Search</h1>
            <form>

                <Select
                    name="form-field-name"
                    value={this.state.value}
                    onChange={this.handleChange}
                    options={options}
                />

在这里它有效

{/* <select class="custom-select custom-select-lg mb-3">
    {this.state.cityName.map(cityName => <option key={cityName.Key}>{cityName.AdministrativeArea.LocalizedName}</option>)}
</select> */}

这就是错误

未处理的拒绝(TypeError):无法读取未定义的属性“LocalizedName”

标签: reactjs

解决方案


如果我的理解是正确的,那么您正在使用react-select.

react-select需要options以下格式的数组,

const options = [
  { value: '', label: '' },
  { value: '', label: '' },
  ...
]

您的选项应采用上述格式。

由于您的数据来自 API,因此您需要首先检查您是否有处于状态的数据,然后仅遍历状态以获取options

let options = [];

if(this.state.cityName && this.state.cityName.length > 0){
   options = this.state.cityName.map((cityName) => {
        return {value: cityName.AdministrativeArea.LocalizedName, label: cityName.AdministrativeArea.LocalizedName};
    })
}

推荐阅读