【问题标题】:React-Select Async is showing error when my search result is empty当我的搜索结果为空时,React-Select Async 显示错误
【发布时间】: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


    【解决方案1】:

    尝试编辑您的 loadOptions 函数以在结果为空的情况下返回空数组而不是字符串:

    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;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      相关资源
      最近更新 更多