[英]React-select does not render data
我正在尝试使用react-select
来制作一个简单的下拉菜单,其中包含来自公共API的值。 但是,即使从API提取似乎正常工作( console.log()
显示所需数据),下拉选择中也没有选项。
我试过跟随这个线程
但是由于我想使用钩子,因此必须进行一些更改。
我使用了线程顶部注释中的第三种方法(在该方法中,您将labelKey
和valueKey
传递为prop,而不是创建新数组),但是下拉列表中只有空字段。
这是来自API的数据的示例
"results:[
{"name":"Algeria","code":"DZ","cities":1,"locations":1,"count":1149},
{"name":"Andorra","code":"AD","cities":2,"locations":3,"count":80963},
{"name":"Argentina","code":"AR","cities":1,"locations":4,"count":14976}
]
这是实际功能的代码
function SearchBar(props) {
const [options, setOptions] = React.useState([]);
function handleChange(e) {
props.setCountryName(e.value);
}
useEffect(() => {
async function FetchData() {
fetch(`https://api.openaq.org/v1/countries?limit=300`, {mode: 'cors'})
.then(res => res.json())
.then(
(result) => {
setOptions(result.results)
})
}
FetchData()
}
,[])
console.log(options);
return(
<Select
className='react-select-container'
placeholder="Choose country"
onChange={handleChange}
labelKey="name"
valueKey="code"
options={options}
/>
)
}
在react-select
您需要告诉label
哪个label
和哪个value
。 如果您在options
数组中没有明确的label
和value
。
<Select
className='react-select-container'
placeholder="Choose country"
onChange={handleChange}
labelKey="name"
valueKey="code"
getOptionLabel={option => {
return option.name;
}}
getOptionValue={option => {
return option.code;
}}
options={options}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.