[当我尝试调用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,并且未执行默认搜索,这就是为什么我得到了模糊后一直在寻找的正确数组的原因。