我有一个围绕搜索栏的包装器组件,它在每次击键时获取建议,然后在选择建议或用户点击输入/搜索时进行搜索。选择搜索值后,我想将该搜索项保存到本地存储,以便我可以重点显示它,就像谷歌一样。这是我的组件的一个片段
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 缺少依赖项:“recentSearches”和“setRecentSearches”。要么包括它们,要么删除依赖数组 react-hooks/exhaustive-deps
。将这两个添加到依赖项数组后,我陷入了无限循环,因为当然 recentSearches
的状态正在设置,导致它重新呈现等等。我想找到一个解决方案来反对添加 //eslint-disable-next-line
因为我觉得我做的事情确实有问题。有谁知道我可以做些什么来防止无限循环和防止 linter 警告?
最佳答案
它有两个作用。
由于您希望利用现有的状态值来更新相同的状态,因此您应该使用回调方法
setRecentSearches(prevRececentSearches => ([searchAttributes.value, ...prevRececentSearches]));
此外,当您完全确定您没有遗漏任何依赖项时,您可以禁用警告。请查看此帖子了解更多详情:How to fix missing dependency warning when using useEffect React Hook?
关于javascript - 在 useEffect 钩子(Hook)中添加依赖导致死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58643805/