【发布时间】:2020-02-26 20:10:13
【问题描述】:
我在搜索栏周围有一个包装器组件,它在每次击键时获取建议,然后在选择建议或用户点击输入/搜索时进行搜索。选择搜索值后,我想将该搜索项保存到本地存储中,以便我可以将其显示为焦点,就像 Google 一样。这是我的组件的 sn-p
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 相反的解决方案,因为我觉得我做的事情确实有问题。有谁知道我可以做些什么来防止无限循环并防止 linter 警告?
【问题讨论】:
-
不要太在意
react-hooks/exhaustive-deps。仅当您想在依赖关系更改时更新值时才合乎逻辑。将其视为建议而非要求。您可能只想做一次事情,并有一个空的[]作为依赖项。这也会引发警告,尽管它毫无意义 -
一种效果会发生很多事情。可能最好将它们分成多种效果。
标签: javascript reactjs react-hooks use-effect