简体   繁体   English

在 useEffect 钩子中添加依赖会导致无限循环

[英]Adding dependency in useEffect hook causes infinite loop

I have a wrapper component around a search bar that fetches suggestions with each keystroke and then searches either when a suggestion is chosen or the user hits enter/search.我在搜索栏周围有一个包装器组件,它通过每次击键获取建议,然后在选择建议或用户点击输入/搜索时进行搜索。 Upon choosing a search value, I want to persist that search item to local storage, so that I can show it on focus, much like Google.选择搜索值后,我想将该搜索项保存到本地存储中,以便我可以将其显示为焦点,就像谷歌一样。 Here is a snippet of my component这是我的组件的片段

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 ( ... );
};

This works fine, but then I get hit with the linting warning: React Hook useEffect has missing dependencies: 'recentSearches' and 'setRecentSearches'. Either include them or remove the dependency array react-hooks/exhaustive-deps这工作正常,但随后我收到了 linting 警告: React Hook useEffect has missing dependencies: 'recentSearches' and 'setRecentSearches'. Either include them or remove the dependency array react-hooks/exhaustive-deps React Hook useEffect has missing dependencies: 'recentSearches' and 'setRecentSearches'. Either include them or remove the dependency array react-hooks/exhaustive-deps . React Hook useEffect has missing dependencies: 'recentSearches' and 'setRecentSearches'. Either include them or remove the dependency array react-hooks/exhaustive-deps Upon adding those two into the dependency array, I get stuck in an infinite loop because of course recentSearches 's state is getting set, causing it to re-render and so on.将这两个添加到依赖项数组中后,我会陷入无限循环,因为recentSearches的 state 正在设置,导致它重新渲染等等。 I'd like to find a solution as oppose to adding // eslint-disable-next-line because I feel there is something truly wrong that I am doing.我想找到一个与添加// eslint-disable-next-line的解决方案,因为我觉得我正在做的事情确实是错误的。 Does anyone know what I could do differently to prevent the infinite loop and prevent the linter warning?有谁知道我可以做些什么来防止无限循环并防止 linter 警告?

There ware two things to it.它有两件事。

Since you wish to make use of the existing state value to update the same state you should use callback approach由于您希望利用现有的 state 值来更新相同的 state 您应该使用回调方法

setRecentSearches(prevRececentSearches => ([searchAttributes.value, ...prevRececentSearches]));

Also when you are absolutely sure that you haven't missed any dependency, you can disable the warning.此外,当您完全确定没有遗漏任何依赖项时,您可以禁用警告。 Please check this post for more details: How to fix missing dependency warning when using useEffect React Hook?请查看这篇文章以获取更多详细信息: How to fix missing dependency warning when using useEffect React Hook?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM