[英]Searchable dropdown in semantic-ui-react does not immediately display full list of options retrieved from 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 清空,并且没有执行默认搜索,这就是为什么我在模糊后得到了我正在寻找的正确数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.