下拉选择,列表的远程搜索、分页
const getList = async (page = 1, curlist = [], value) => {
const res = await get('xxxxxxxxx', {
keyWords: value !== undefined ? value : state.searchValue,
currentPage: page,
numPerPage: 100,
});
setState({
loading: false,
curPage: page,
total: res?.data?.pageInfo?.totalRecord,
});
setList([...curlist, ...(res?.data?.list || [])]);
};
const getListBefore = useCallback(
(_props) => {
// _props传入 分页, 现有列表,输入框内容
const { page, list, value } = _props;
// 当不是第一页切 列表数量大于等于总数时终止掉
if (page !== 1 && list?.length >= state.total) {
return message.warning('没有更多数据了');
} else if (state.loading) {
// 如果处于加载中也终止掉
return;
}
// 请求,加载中
setState({ loading: true });
// 请求接口
getList(page, list, value);
},
// callback监听 总数,是否加载中,输入框内容
[state.total, state.loading, state.searchValue]
);
// 滚动事件
const onPopupScroll = useCallback(
(event) => {
event.persist();
const { target } = event;
if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
// 调用加载数据,传入需求请求的分页
getListBefore({
page: state.curPage + 1,
list: list,
});
}
},
[list]
);
// 选择器输入框改变
const onSearch = useCallback(
(event) => {
if (searchFlag) {
clearTimeout(searchFlag);
}
// 防抖 0.5后请求数据,把分页重置回1,列表重置
searchFlag = setTimeout(() => {
setState({
searchValue: event,
});
getListBefore({
page: 1,
list: [],
value: event,
});
clearTimeout(searchFlag);
}, 500);
},
[list]
);
React.useEffect(() => {
getList();
}, []);
<Select showSearch onSearch={onSearch} onChange={handleChange} onPopupScroll={onPopupScroll} filterOption={false} placeholder="请选择负面清单">
{list &&
list.map((item) => (
<Option value={item?.listId} key={item?.listId}>
{item?.name}
</Option>
))}
{state.loading && (
<Option value="loading" disabled>
<Spin>加载中</Spin>
</Option>
)}
</Select>