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

时间:2019-10-31 12:53:16

标签: javascript reactjs react-hooks use-effect

我在搜索栏周围有一个包装器组件,该组件可通过每次击键获取建议,然后在选择建议或用户按下Enter /搜索时进行搜索。选择搜索值后,我想将该搜索项保留到本地存储中,以便像Google一样将其重点关注。这是我的组件的片段

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

这很好,但是随后我收到了掉毛警告: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相对的解决方案,因为我觉得自己确实在做错事。有谁知道我可以做些什么来防止无限循环和防止短绒警告?

1 个答案:

答案 0 :(得分:1)

有两件事情。

由于您希望利用现有状态值来更新同一状态,因此应使用回调方法

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

此外,如果您完全确定自己没有错过任何依赖项,则可以禁用该警告。请查看此帖子以获取更多详细信息:How to fix missing dependency warning when using useEffect React Hook?