私はreact-selectを使用していますが、表示するオプションをハードコードしたくありませんが、オプションは、私がAPIから取り出すデータです。私は本当に何かを見つけることができませんし、私がしようとしていることは何も表示されないので動作しません。誰でも知っていますか?ありがとう!!!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", …}
...
あなたは 'cities:res.Cities.name'を割り当てています。これは正しいですか?または '都市:res.Cities'? –
はい、残念ですが都市:res.Cities – javascripting