当我的搜索结果为空时,React-Select Async 显示错误
React-Select Async is showing error when my search result is empty
我正在尝试实现一个异步反应-select 下拉菜单,如果用户在下拉菜单中键入内容,将会有搜索结果 return 来自搜索 API。使用我的代码,如果我搜索的内容有结果,它工作正常,但如果没有结果,我将得到 props.options.map is not a function
错误。
如果没有结果,我该如何处理这个错误?
错误
如果有任何相关结果,这就是 API return 的内容:
如果没有找到结果,API 将 return 执行以下操作:
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;
尝试将 loadOptions
函数编辑为 return 空数组而不是字符串,以防结果为空:
const loadOptions = async () => {
const res = await fetch(`https://example-api.com/search_user?value=${query}`);
const data = await res.json();
const results = data.Result;
if (results === "No result found.") {
// Empty result, return an empty array instead of a string
return [];
}
return results;
};
我正在尝试实现一个异步反应-select 下拉菜单,如果用户在下拉菜单中键入内容,将会有搜索结果 return 来自搜索 API。使用我的代码,如果我搜索的内容有结果,它工作正常,但如果没有结果,我将得到 props.options.map is not a function
错误。
如果没有结果,我该如何处理这个错误?
错误
如果有任何相关结果,这就是 API return 的内容:
如果没有找到结果,API 将 return 执行以下操作:
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;
尝试将 loadOptions
函数编辑为 return 空数组而不是字符串,以防结果为空:
const loadOptions = async () => {
const res = await fetch(`https://example-api.com/search_user?value=${query}`);
const data = await res.json();
const results = data.Result;
if (results === "No result found.") {
// Empty result, return an empty array instead of a string
return [];
}
return results;
};