简体   繁体   English

React Hooks Exhaustive-deps 异步无限循环

[英]React Hooks Exhaustive-deps async infinite Loop

I have the following component:我有以下组件:

import React, { useState, useEffect } from "react";

const App = () => {
    const [data, setData] = useState<null | any[]>(null);
    const [checked, setChecked] = useState(false);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        setLoading(true);

        (async () => {
            if (data) {
                // Could do something else here if data already exsisted
                console.log("Data exists already");
            }

            const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
            const json = await ret.json();
            setData(json);
            setLoading(false);
        })();

    }, [checked]);

    return (
        <>
            <h1>useEffect Testing {loading && " ⌛"}</h1>
            <hr />
            <input type="checkbox" checked={checked} onChange={(e) => setChecked(e.target.checked)} />
            <pre style={{ fontSize: "0.8em" }}>{JSON.stringify(data)}</pre>
        </>
    );
};

export default App;

Currently, my if(data) is pointless however if I wanted to check the current data state and then run an asynchronous function based on the state the eslint(react-hooks/exhaustive-deps) tells me the hook is missing the data dependency, which it is. Currently, my if(data) is pointless however if I wanted to check the current data state and then run an asynchronous function based on the state the eslint(react-hooks/exhaustive-deps) tells me the hook is missing the data dependency,它是。 The problem comes when I add data to the dependency list causing an infinite loop.当我将数据添加到导致无限循环的依赖项列表时,问题就出现了。

Any idea how to resolve this?知道如何解决这个问题吗? It feels like it should be fairly simple pattern however everything I find recomends using the extended setState(prev => prev + 1) overload which doesn't help me in this case.感觉它应该是相当简单的模式,但是我发现的所有建议都使用扩展的setState(prev => prev + 1)重载,在这种情况下对我没有帮助。

You are setting data and also reading it in the effect.您正在设置data并在效果中读取它。 This will cause you an infinite loop unless you manually stop it.除非您手动停止它,否则这将导致您陷入无限循环。 Here are a few solutions.这里有一些解决方案。

Return if there is data instead of modify it:如果有数据则返回而不是修改它:

useEffect(() => {
    setLoading(true);

    (async () => {
        if (data) {
            // Could do something else here if data already exsisted
            console.log("Data exists already");
            return;
        }

        const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
        const json = await ret.json();
        setData(json);
        setLoading(false);
    })();

}, [checked, data]);

Remove your reliance on data in the effect that sets it (what I'd do):消除您对设置它的效果中的data的依赖(我会做什么):

useEffect(() => {
    setLoading(true);

    (async () => {
        const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
        const json = await ret.json();
        setData(json);
        setLoading(false);
    })();

}, [checked]);

useEffect(() => {
        if (data) {
            // Could do something else here if data already exsisted
            console.log("Data changed and exists!");
        }
}, [data]);

Or you can manually do something that stops the infinite loop.或者您可以手动执行一些停止无限循环的操作。

useEffect(() => {
    if (loading || data) {
      console.log('Do something with loading or data, but do not modify it!')
      return;
    }

    setLoading(true);

    (async () => {
        const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
        const json = await ret.json();
        setData(json);
        setLoading(false);
    })();
}, [checked, data]);

暂无
暂无

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

相关问题 react-hooks/exhaustive-deps 警告还是无限循环? - react-hooks/exhaustive-deps warning or infinite loop? React 使用 function 使用 state 的异步钩子穷举无限循环 - React hooks exhaustive-deps infinite loop with async function which uses state 由 axios 取消令牌引起的 react useEffect hook 无限循环 [react-hooks/exhaustive-deps] - react useEffect hook infinite loop caused by axios cancel token [react-hooks/exhaustive-deps] 使用 useCallback 响应无限更新循环(react-hooks/exhaustive-deps) - React infinite update loop with useCallback (react-hooks/exhaustive-deps) 如何使用React Hooks进行获取; ESLint强制执行“穷举下降”规则,这会导致无限循环 - How to do fetch with React Hooks; ESLint enforcing `exhaustive-deps` rule, which causes infinite loop ESLint 希望 setSate 作为 useEffect 的依赖,但这会导致无限循环(react-hooks/exhaustive-deps) - ESLint wants setSate as a dependency for useEffect but this causes an infinite loop (react-hooks/exhaustive-deps) react-hooks/exhaustive-deps 警告 - react-hooks/exhaustive-deps warning 是否有一个带有useEffect的无限滚动的实现,它不会触发react-hooks / exhaustive-deps lint警告? - Is there an implementation of infinite scroll with useEffect that doesn't trigger the react-hooks/exhaustive-deps lint warning? 遵守 react-hooks/exhaustive-deps 会导致无限循环和/或大量 useCallback() - Obeying react-hooks/exhaustive-deps leads to infinite loops and/or lots of useCallback() 我如何正确使用 useEffect 进行异步获取调用和反应? 反应钩子/详尽的deps - How do i properly use useEffect for a async fetch call with react? react-hooks/exhaustive-deps
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM