我正在使用 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
带有初始选项的 Async 下拉列表,但是当我使用搜索 API 时,我不知道如何加载初始选项,该 API 只有在我输入内容后才会获得特定的结果列表。当用户单击编辑时,我想要这样的东西,这将显示数据库中保存的员工姓名(可以是单个或多个选项):
这是供引用的代码和框,但我只使用了一个虚假的 API 链接:
编辑:
供@Pitter 引用:
最新更新:
我尝试使用
value
Pitter 提到的选项,但不知何故,即使我尝试取消选择或清除选项以及当我尝试搜索并选择新选项时,输入的选项也不会改变。最终更新
最后我让它工作了!我只需要设置
value
props/component 到一个状态,并有一个用于 onChange
的 handleChange 方法props/component 来改变值的状态。它实际上与通常的 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)}
/>
);
最佳答案
我正在阅读 ReactSelect github 上的问题并找到了解决方案。
您需要在“值”中传递对象。看看下面的例子。
<AsyncSelect
cacheOptions
defaultOptions
value = {1} // this won't work
value = {{value: 1, label: "black"}}
loadOptions={promiseOptions}
onInputChange={this.handleInputChange}
/>
引用:https://github.com/JedWatson/react-select/issues/3761
关于reactjs - 使用搜索 API 时,如何使用编辑项功能的初始选项加载 React-select Async?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69293081/