语义-ui-react中的可搜索下拉列表不会立即显示从API检索到的选项的完整列表



当我试图调用API来填充语义UI的选项时,它首先显示一部分选项,为了显示完整列表,我必须首先单击下拉列表外部(模糊(,然后再次单击下拉列表内部。

我已经陷入这种困境有一段时间了,我真的想不出其他什么可以尝试的,有人知道它为什么会这样吗?

这是代码:

import React, { Component } from 'react';
import { Dropdown } from 'semantic-ui-react';
import axios from 'axios';
let typingTimer;
class App extends Component {
constructor(props) {
super(props);
this.state = {
creators: [],
creatorsLoading: true,
selectedCreator: null
};
this.searchCreators = this.searchCreators.bind(this);
this.setCreatorsState = this.setCreatorsState.bind(this);
this.changeCreator = this.changeCreator.bind(this);
}
componentDidMount() {
this.searchCreators();
}
setCreatorsState(res) {
this.setState({
creators: res.data.map((user) => {
return { text: `${user.name} (${user.country})`, value: user.id };
}),
creatorsLoading: false
});
}
searchCreators(searchQuery) {
if (searchQuery === '') {
this.setState({ creatorsLoading: false });
return null;
}
this.setState({ creatorsLoading: true });
const args = {
params: {
'search_query: searchQuery.trim();
}
};
axios
.get(url, args)
.then((res) => {
if ('error' in res)
return this.setState({ creatorsLoading: false });
else {
this.setCreatorsState(res.data);
}
})
.catch((err) => this.setState({ creatorsLoading: false }));
}
delayExecute(text) {
//Detect keystroke and only execute after the user has finish typing
clearTimeout(typingTimer);
typingTimer = setTimeout(() => {
return this.searchCreators(text);
}, 700);
return true;
}
changeCreator(value) {
if (value) this.setState({ selectedCreator: value });
else this.setState({ selectedCreator: null });
}
render() {
const {creators, creatorsLoading, selectedCreator} = this.state;
return (
<Dropdown
selectOnBlur={false}
loading={creatorsLoading || false}
clearable
onChange={(_, data) => this.changeUser(data.value)}
onSearchChange={(_, data) => this.delayExecute(data.searchQuery)}
placeholder="Creators"
fluid
selection
search
value={selectedCreator}
options={creators}
/>
);
}
}
export default App;

我终于发现了问题所在,所以如果有人在这里偶然发现类似的东西,那就是:

语义UI的可搜索下拉列表默认情况下执行搜索,因此我将searchQuery发送到API,并根据该searchQuery检索用户数组,然后下拉列表在检索到的数组中为同一个searchQuery执行另一个搜索。由于我放在选项中的文本与我在API中搜索的标准不同,所以我得到了不同的结果。

this.setState({
creators: res.data.map((user) => {
return { text: `${user.name} (${user.country})`, value: user.id };
}),
creatorsLoading: false
});

由于我在下拉列表外单击时使用的是selectOnBlur={false},searchQuery被清空,并且没有执行默认搜索,这就是为什么我在模糊后得到了我想要的正确数组。

我花了很长时间才弄明白。问题实际上在于搜索功能的工作方式,请参阅:https://github.com/Semantic-Org/Semantic-UI-React/issues/3932

将搜索道具更改为search={(i) => i},一旦返回远程选项,它将停止过滤结果。

最新更新