【发布时间】:2021-09-18 17:43:45
【问题描述】:
我正在尝试实现一个异步反应选择下拉菜单,如果用户在下拉菜单中输入,搜索 API 将返回搜索结果。如果我搜索的内容有结果,我的代码可以正常工作,但如果没有结果,我会收到props.options.map is not a function 错误。
当没有结果时,我可以做些什么来处理这个错误?
错误
如果有任何相关结果,这就是 API 返回的内容:
如果没有找到结果,这就是 API 将返回的内容:
SearchUserDropdown.js
import { useState } from 'react';
import AsyncSelect from 'react-select/async';
import makeAnimated from 'react-select/animated';
const SearchUserDropdown = ({ setGroupMembers }) => {
const [query, setQuery] = useState('')
//get animated components wrapper
const animatedComponents = makeAnimated();
const loadOptions = async () => {
const res = await fetch(`https://example-api.com/search_user?value=${query}`);
const data = await res.json();
const results = data.Result;
return results;
};
return (
<AsyncSelect
cacheOptions
isMulti
components={animatedComponents}
getOptionLabel={(e) => e.fullname}
getOptionValue={(e) => e.empId}
loadOptions={loadOptions}
onInputChange={(value) => setQuery(value)}
onChange={(value) => setGroupMembers(value)}
/>
);
};
export default SearchUserDropdown;
【问题讨论】:
标签: reactjs react-select