Javascript 在react select Async中设置值而不添加额外状态
我构建了一个功能组件DepartmentSelect,它使用react-select-Async允许用户从下拉列表中选择一个部门。我想在道具中传递所选部门的id 我有一个有效的例子,但似乎我复制了逻辑。我向loadOptions Resact select prop传递了一个承诺,并将选项存储在状态中。我在DepartmentSelect props中有所选部门的departmentId,并且我正在状态中存储所选值Javascript 在react select Async中设置值而不添加额外状态,javascript,reactjs,asynchronous,default-value,react-select,Javascript,Reactjs,Asynchronous,Default Value,React Select,我构建了一个功能组件DepartmentSelect,它使用react-select-Async允许用户从下拉列表中选择一个部门。我想在道具中传递所选部门的id 我有一个有效的例子,但似乎我复制了逻辑。我向loadOptions Resact select prop传递了一个承诺,并将选项存储在状态中。我在DepartmentSelect props中有所选部门的departmentId,并且我正在状态中存储所选值 //... imports and getOptionLabel removed
//... imports and getOptionLabel removed for brevity
const getOptionValue = (option) => {
return option.id;
};
interface Props {
departmentId: string,
onChange: (number) => void
}
let options = [];
const DepartmentSelect = (props: Props) => {
const [value, setValue] = useState(
options.find(o => o.id == props.departmentId)
);
const [isLoading, setLoading] = useState(true);
const handleChange = (option, action) => {
const id = option && option.id;
setValue(options.find(o => o.id == id));
props.onChange(id);
};
const loadOptions = () => {
return ky.get('/sbm/departments.json')
.then(r => r.json())
.then(json => {
options = json;
setValue(options.find(o => o.id == props.departmentId));
setLoading(false);
return json;
});
};
return (
<AsyncSelect
defaultOptions
getOptionValue={getOptionValue}
loadOptions={loadOptions}
onChange={handleChange}
value={value}
/>
);
};
export default DepartmentSelect;
如果props.onChange(id)代码>设置departmentId,那么为什么不将AsyncSelect的value属性设置为props.departmentId?
{
departmentId: string,
bill_cd: string,
name: string
}