使用ant Select,我编写了一个组件,它有两种模式. 首先:它接受选项,即 Select 数据.并显示它(此部件工作正常). 第二:它接受一个SELECT_url,组件本身发送从服务器获取数据的请求.一切正常,除了我搜索字符时,有时列表弹出窗口不显示!这是出乎意料的.我确信数据到达了setOptions,甚至_Options也有数据,但它没有显示出来.但是,当我搜索数字时,它工作得很好!
我是新手,我以前用过Vuejs.有没有可能我没有正确使用react ?
一切正常,除了我搜索字符时,有时列表弹出窗口不显示!这是出乎意料的.我确信数据到达了setOptions,甚至_Options也有数据,但它没有显示出来.但是,当我搜索数字时,它工作得很好!
以下是我的孔组件:
import React, {useEffect, useState} from "react";
import {Select, Spin} from "antd";
import {SelectOption} from "../../@types/app";
interface CustomSelectProps {
options?: SelectOption[],
placeholder?: string,
select_url?: string
}
const CustomSelect: React.FC<CustomSelectProps> = (
{
options,
placeholder = "انتخاب کنید",
select_url
}
) => {
const [_options, setOptions] = useState<undefined | SelectOption[]>(options);
const [nextPageUrl, setNextPageUrl] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(false);
useEffect(() => {
if (select_url) {
search()
} else if (options && !select_url) {
setOptions(options);
} else {
// todo: notify user, that this component needs at least one of options || select_url.
console.log("specify data. SELECT");
}
}, []);
const search = async (input: string = '') => {
if (!select_url) return;
setLoading(true);
setOptions(() => []);
const url = `${select_url}?search=${input}&page=1`;
try {
const response = await fetch(url);
if (!response.ok) {
return new Error(`Network response was not ok (${response.status})`);
}
const data = await response.json();
setNextPageUrl(data.next);
setOptions(prevOptions => [...prevOptions, ...data.data]);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
setLoading(false);
}
};
const handlePopupScroll = async (e: React.UIEvent<HTMLDivElement>) => {
if (!select_url) return;
const popupContainer = e.currentTarget;
const isAtEndOfScroll = popupContainer.scrollTop + popupContainer.clientHeight === popupContainer.scrollHeight;
if (isAtEndOfScroll && nextPageUrl && !loading) {
try {
const res = await (await fetch(nextPageUrl)).json();
setNextPageUrl(res.next);
const {data} = res;
setOptions((prevState) => {
return [...prevState, ...data];
});
} catch (e) {
console.log(e);
} finally {
setLoading(false);
}
}
}
// filter options based on user input in client mode.
const handleFilterOption = (input: string, option?: SelectOption) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase());
return (
<Select
options={_options}
placeholder={placeholder}
showSearch={true}
filterOption={select_url ? undefined : handleFilterOption}
onSearch={search}
notFoundContent={loading ? <Spin size="small"/> : null}
virtual={true}
onPopupScroll={handlePopupScroll}
>
</Select>
);
}
export default CustomSelect;
以下是数据的来源:
[
{ label: "test", value: "value", key: "1" },
]