[英]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.