React-Select Async搜索结果为空时报props.options.map is not a function错如何解决
报错原因
props.options.map is not a function 属于类型错误,触发原因是:react-select 的 AsyncSelect 组件要求 loadOptions 回调必须返回数组类型数据,当搜索无匹配结果时,你的接口返回的 data.Result 不是数组(大概率为 null、undefined 或空对象),组件内部调用 options.map 遍历选项时无法识别非数组类型,进而抛出错误。
修复方案
只需对 loadOptions 的返回值增加类型校验兜底,同时可补充异常捕获、无结果提示优化体验,修改后的完整代码如下:
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 () => { try { const res = await fetch(`https://example-api.com/search_user?value=${query}`); const data = await res.json(); const results = data.Result; // 类型校验:非数组统一兜底返回空数组 return Array.isArray(results) ? results : []; } catch (err) { // 接口请求异常也返回空数组,避免页面崩溃 console.error('用户搜索失败:', err) return [] } }; return ( <AsyncSelect cacheOptions isMulti components={animatedComponents} getOptionLabel={(e) => e.fullname} getOptionValue={(e) => e.empId} loadOptions={loadOptions} onInputChange={(value) => setQuery(value)} onChange={(value) => setGroupMembers(value)} // 可选:自定义无匹配结果时的提示文案 noOptionsMessage={() => '暂无匹配用户'} /> ); }; export default SearchUserDropdown;
内容的提问来源于stack exchange,提问作者Lance
相关产品推荐
相关产品推荐

