我正在使用primereact的自动完成组件。挑战在于,我不想将选项数组设置为组件加载时的状态;但相反,当用户输入前3个字母时,我会启动一个api调用,然后将响应设置为选项数组(这是因为否则数组可能很大,我不想膨胀状态内存(。
const OriginAutocomplete = () => {
const [origins, setOrigins] = useState([]);
const [selectedOrigin, setSelectedOrigin] = useState(null);
const [filteredOrigins, setFilteredOrigins] = useState([]);
useEffect(() => {
if (!selectedOrigin || selectedOrigin.length < 3) {
setOrigins([]);
}
if (selectedOrigin && selectedOrigin.length === 3) {
getOrigins(selectedOrigin).then(origins => {
setOrigins([...origins]);
});
}
}, [selectedOrigin, setOrigins]);
const handleSelect = (e) => {
//update store
}
const searchOrigin = (e) => {
//filter logic based on e.query
}
return (
<>
<AutoComplete
value={selectedOrigin}
suggestions={ filteredOrigins }
completeMethod={searchOrigin}
field='code'
onChange={(e) => { setSelectedOrigin(e.value) }}
onSelect={(e) => { handleSelect(e) }}
className={'form-control'}
placeholder={'Origin'}
/>
</>
)
}
现在的问题是,当我键入3个字母时会触发调用,但只有当我键入第4个字母时才会列出选项。那也没关系,事实上,当我键入2个字母时,我试图更改代码以触发呼叫;但是,只有当我在api调用完成后键入第三个字母时,这才能正常工作,即,我键入2个字母,等待调用完成,然后键入第3个字母。
当选项数组发生更改时,如何显示选项?
我尝试在回调上设置filteredOrigins
getOrigins(selectedOrigin).then(origins => {
setOrigins([...origins]);
setFilteredOrigins([...origins])
});
但它显然不起作用。
想明白了。张贴答案,以防有人思考同样的问题。我将useEffect
中的代码移到了searchOrigin
函数中。
所以searchOrigin的功能如下:
const searchOrigin = (e) => {
const selectedOrigin = e.query;
if (!selectedOrigin || selectedOrigin.length === 2) {
setOrigins([]);
setFilteredOrigins([]);
}
if (selectedOrigin && selectedOrigin.length === 3) {
getOrigins(selectedOrigin).then(origins => {
setOrigins([...origins]);
setFilteredOrigins(origins);
});
}
if (selectedOrigin && selectedOrigin.length > 3) {
const filteredOrigins = (origins && origins.length) ? origins.filter((origin) => {
return origin.code
.toLowerCase()
.startsWith(e.query.toLowerCase()) ||
origin.name
.toLowerCase()
.startsWith(e.query.toLowerCase()) ||
origin.city
.toLowerCase()
.startsWith(e.query.toLowerCase())
}) : [];
setFilteredOrigins(filteredOrigins);
}
}