我正在使用 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>
)
}
}
Data( this.state.cities 是一个对象数组,看起来像:
{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}
...