我有一个围绕搜索栏的包装组件,它在每次击键时获取建议,然后在选择建议或用户点击enter/search时进行搜索。在选择搜索值时,我想将该搜索项保存到本地存储中,这样我就可以像谷歌一样集中显示它。这是我的组件的一个片段
export default function App() {
const [results, resultsLoading, resultsError, setParams] = useFetch();
const [suggestions, ,suggestionsError, setSuggestionsParams] = useFetch();
const [showSearchSuggestions, setShowSearchSuggestions] = useState<boolean>(true);
const [recentSearches, setRecentSearches] = useLocalStorage('recent_searches', []);
const [searchAttributes, setSearchAttributes] = useState<SearchAtrributesInterface>({
value: '',
fetchType: SEARCH_FETCH_TYPES.SUGGESTIONS
});
useEffect(() => {
const getSearchSuggestions = () => setSuggestionsParams(getAutoCompleteURL(searchAttributes.value));
const getSearchResults = () => {
setParams(getSearchURL(searchAttributes.value));
setShowSearchSuggestions(false);
};
if (searchAttributes.value) {
if (searchAttributes.fetchType === SEARCH_FETCH_TYPES.SUGGESTIONS) {
getSearchSuggestions();
} else {
getSearchResults();
setRecentSearches([searchAttributes.value, ...recentSearches])
}
}
}, [searchAttributes, setParams, setSuggestionsParams]);
return ( ... );
};
这很好,但随后我收到了linting警告:React Hook useEffect has missing dependencies: 'recentSearches' and 'setRecentSearches'. Either include them or remove the dependency array react-hooks/exhaustive-deps
。当把这两个添加到依赖数组中时,我陷入了一个无限循环,因为recentSearches
的状态当然被设置了,导致它重新渲染等等。我想找到一个解决方案,而不是添加// eslint-disable-next-line
,因为我觉得我做的确实有问题。有人知道我能做些什么不同的事情来防止无限循环和防止门楣警告吗?
有两件事。
由于您希望利用现有的状态值来更新相同的状态,因此应该使用回调方法
setRecentSearches(prevRececentSearches => ([searchAttributes.value, ...prevRececentSearches]));
此外,当您确信没有遗漏任何依赖项时,可以禁用警告。请查看此帖子了解更多详细信息:如何修复使用useEffect React Hook时丢失的依赖项警告?