【发布时间】:2021-11-16 10:38:41
【问题描述】:
我正在使用 React-Select 的 Async Select 来实现一个下拉菜单,用户可以在其中搜索大量数据。他们在搜索时会看到员工的姓名,并且可以选择多个员工。
React-select 将使用我拥有的搜索 API 获取数据,并将使用此方法在后面插入查询:
const loadOptions = async () => {
const res = await fetch(`https://example.com/search_user?value=${query}`);
const data = await res.json();
const results = data.Result;
if (results === 'No result found.') {
return [];
}
return results;
};
我想要的是员工 ID 和他们的全名,然后在用户提交表单后将这两个信息发布到 API。
所有这些都可以完美运行,但现在我想实现一个编辑功能,用户可以在其中编辑已保存到数据库中并创建的Group Members。
所以我自然需要使用初始选项加载react-select 的异步下拉列表,但我不知道如何在使用搜索 API 时加载初始选项,该 API 只会获得特定列表输入内容后的结果。
当用户单击编辑时,我想要这样的东西,这将显示数据库中保存的员工姓名(可以选择单个或多个选项):
这是供参考的代码框,但我只使用了一个虚假的 API 链接:
编辑:
最新更新:
我尝试使用 Pitter 提到的 value 选项,但不知何故,即使我尝试取消选择或清除选项以及尝试搜索并选择新选项时,输入的选项也没有改变。
最终更新
最后我让它工作了!我所需要的只是将value props/component 设置为一个状态,并为onChange props/component 设置一个handleChange 方法来更改值的状态。它实际上与通常的 react-select 的 Select 相同。
下面是我用过的代码:
// Creating a state for the selected options
const [selectedOption, setSelectedOption] = useState('')
// To set/load the initial value that is saved for the current item to edit/manage
useEffect(() => {
// Your code to get the initial values, then set it to the state that you've created
setSelectedOption(initial)
}, [modalInfo]);
// A handle change method to change the selected value/options
const handleChange = (selectedOption) => {
setSelectedOption(selectedOption);
};
// Then all you need is the onChange method to use the handleChange and
// having the value set to the state that you've created
return (
<AsyncSelect
onChange={handleChange}
value={selectedOption}
loadOptions={loadOptions}
cacheOptions
defaultOptions
isMulti
components={animatedComponents}
getOptionLabel={(e) => e.fullname}
getOptionValue={(e) => e.empId}
onInputChange={(value) => setQuery(value)}
/>
);
【问题讨论】:
-
您是否尝试过使用“DefaultOption”?我认为您可以向此选项提供您的数据。文档:react-select.com/async
-
@Pitter 我没有尝试过“defaultOptions”,我现在会尝试研究一下。
-
@Pitter 不幸的是,在阅读完文档后,我仍然无法使其适用于我的场景。
标签: reactjs react-select