React Semantic UI多选搜索Dropdown远程搜索时已选条目消失问题
问题根因
Semantic UI 多选 Dropdown 组件只会渲染options数组中存在的对应值的选中项,你每次搜索触发接口请求后直接覆盖了整个options数组,之前已经选中、但不在新搜索结果里的选项就从options里消失了,组件找不到对应条目展示选中状态,看起来就像选中的条目消失了。
解决方案
核心逻辑是每次拿到新的搜索结果后,把当前已经选中的选项和新搜索结果合并去重后再赋值给options,保证已选中的项永远存在于options数组中。
修改后的实现代码
constructor(props) { super(props); this.state = { field1: [], options: [], isFetching: false } } handleDropdown = (event, data) => { this.setState({ field1: data.value }); } handleSearchDropdown = (e, { searchQuery }) => { this.setState({ isFetching: true }) fetch(`${'/searchgrants?query='}${searchQuery}`) .then((response) => response.json()) .then(dataList => { // 取出当前已选中的选项 const selectedOptions = this.state.options.filter(opt => this.state.field1.includes(opt.value)); // 合并已选选项和新搜索结果,按value去重 const mergedOptions = [...selectedOptions, ...dataList].reduce((acc, cur) => { if(!acc.find(item => item.value === cur.value)) { acc.push(cur); } return acc; }, []); this.setState({ options: mergedOptions , isFetching: false}); }); } render() { return ( <Form.Field control={Dropdown} onChange={this.handleDropdown} options={this.state.options} value={this.state.field1} fluid search selection required minCharacters={1} onSearchChange={this.handleSearchDropdown} multiple loading={this.state.isFetching} /> ) }
补充说明
如果你的接口返回的搜索结果本身就包含所有已选中的选项,无需额外合并逻辑,直接检查接口返回是否正常即可。上述方案适用于接口仅返回和搜索关键词匹配的结果、不包含未匹配的已选选项的场景。
内容的提问来源于stack exchange,提问作者Abdoulaye Diallo
相关产品推荐
相关产品推荐

