React Select - How to show / iterate through data from api call in option instead of hardcoding options?

前端 未结 3 642
悲哀的现实
悲哀的现实 2021-02-09 09:57

I am using react-select and I don\'t want to hard code the options which should be displayed, but options is data I am fetching from an api. I can\'t really find anything and wh

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-09 10:02

    In your return component you can simply pass the cities that is fetched from api as

    import Select from 'react-select';
    import {availableCities} from '../utils/api.js';
    
    let isLoadingExternally = false;
    
    class App extends React.Component {
    
        constructor(props) {
        super(props);
        this.state = {
            selectedOption: '',
            clearable: true,
            cities: [],
        } 
    }
    componentDidMount() {
        isLoadingExternally = true;
        availableCities()
            .then(res => {
                this.setState({
                    cities: res.Cities.name
                }, () => {
                    isLoadingExternally = false;
                })
                console.log("hello", this.state.cities)
            })
    }
    
    handleChange(selectedOption) {
        this.setState({selectedOption});
    }
    render(){
    return (
        
    提交评论

提交回复
热议问题