React Hooks Exhaustive-deps异步无限循环

时间:2020-07-30 14:07:43

标签: reactjs typescript react-hooks eslint-plugin-react-hooks

我有以下内容:

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;

当前,我的if(data)是毫无意义的,但是如果我想检查当前data的状态,然后基于 eslint(react-hooks /

告诉我该钩子缺少data依赖项。当我将数据添加到依赖项列表时会导致无限循环。

任何想法如何解决这个问题?感觉这应该是相当简单的模式,但是我发现的所有内容都建议使用扩展的setState(prev => prev + 1)重载,这种情况下对我没有帮助。

1 个答案:

答案 0 :(得分:0)

您正在设置data并同时阅读效果。这将导致无限循环,除非您手动将其停止。这是一些解决方案。

返回是否有数据而不是修改它:

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]);

消除对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]);

或者您可以手动执行一些操作来停止无限循环。

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]);
相关问题
最新问题