jav*_*ing 5 reactjs react-select
我正在使用react-select,并且我不想对应该显示的选项进行硬编码,但是选项是我从api获取的数据。我真的找不到任何东西,而且由于没有显示任何内容,所以我尝试执行的操作不起作用。有谁知道?谢谢!!!
api.js:
export function availableCities() {
return axios.get('/cities').then(function (response) {
return response.data;
})
}
Run Code Online (Sandbox Code Playgroud)
零件:
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
数据(this.state.cities是一个对象数组,看起来像:
{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}
...
Run Code Online (Sandbox Code Playgroud)
这里的问题来自数组中的对象。react-select需要具有以下键的对象数组才能理解它:value和label。
因此,在渲染中,您可以替换
let options = this.state.cities.map(function (city) {
return city.name;
})
Run Code Online (Sandbox Code Playgroud)
通过,例如
let options = this.state.cities.map(function (city) {
return { value: city.countryCode, label: city.name };
})
Run Code Online (Sandbox Code Playgroud)
或者,就像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>
)
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助你!
| 归档时间: |
|
| 查看次数: |
5759 次 |
| 最近记录: |