我有一个调用 api 来获取结果的输入。我一直在去抖动,以便只有在特定时间之后才会调用 api。这工作正常。但是我想在 textinput 文本为空后重置结果。当 textinput 为空时,promise 已经调用并返回结果。这是我的 jsfiddle 链接。我使用了一个标志 abort 但该标志值没有更新,因为该函数处于事件循环中。 这是我的 jsfiddle https://jsfiddle.net/foya6gc1/
const App = () => {
const [searchText, setSearchText] = React.useState('');
const [ searchResult, setSearchResult ] = React.useState([]);
const [ selectedWords, setSelectedWords ] = React.useState([]);
const [searchBoxActive, setSearchBoxActive ] = React.useState('search-box');
const [showMenu, setShowMenu ] = React.useState(false);
let abort = false;
React.useEffect(() => {
console.log('useEffec');
if(!searchText) {
console.log('useeffect', searchText);
setSearchResult([]);
handleSearch.cancel();
}
}, [searchText]);
const handleChange = async e => {
setSearchText(e.target.value);
console.log('entered text', e.target.value);
if(!e.target.value) {
abort = true;
setSearchResult([]);
console.log('abort before', abort);
handleSearch.cancel();
}else {
abort = false;
console.log('abort before2', abort);
handleSearch(e.target.value);
}
}
const handleSearch = _.debounce(async term => {
console.log('enter debounce');
const result = await getSuggestions(term);
console.log('abort', abort);
if(abort) { //Here abort is always coming as false
setSearchResult([]);
return;
}
console.log('searchText',searchText);
if(!searchText) return;
setSearchResult(result);
}, 300, {
leading: true,
trailing: false
});
const handleSelect = word => {
const newWords = [...selectedWords, word];
setSelectedWords(newWords);
setSearchText('');
setSearchResult([]);
}
const handleFocusIn = () => {
setSearchBoxActive('search-box active');
setShowMenu(true);
}
const handleFocusOut = () => {
setSearchBoxActive('search-box');
setShowMenu(false);
}
return (<div>
<div className={searchBoxActive}>
<div className="search-control">
{selectedWords.map(word =>
<div className="css-1rhbuit-multiValue">
<div className="css-12jo7m5">{word}</div>
</div>)}
<div className="input-wrap">
<input type="text" value={searchText}
onFocus={handleFocusIn}
onBlur={handleFocusOut}
onChange={handleChange}/>
</div>
</div>
</div>
{showMenu && <div className="search-results">
{searchResult.length > 0 ? <ul>
{
searchResult.map(result => <li onClick={() => handleSelect(result)}>{result}</li>)
}
</ul> : 'No Result'}
</div> }
</div>)
}
ReactDOM.render(<App/>, document.getElementById('root'));
答案 0 :(得分:0)
我使用 ref 解决了它。我正在检查输入值是否为空,然后重置结果。
https://jsfiddle.net/foya6gc1/1/
if(!inputRef.current.value) {
setSearchResult([]);
return;
}