`useMemo` 导致钩子无限地连续触发。

huangapple go评论65阅读模式
英文:

useMemo causes hook to continuously fire infinitely

问题

我有一个自定义的React Hook,用于从子图端点查询数据。它简单地返回一个对象数组。

const useAllLPTokens = (): GraphQLResponse<LPTokens> => {
    const [status, setStatus] = useState<number>(0);
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<any>();
    const [response, setResponse] = useState<any>();
    const [payload, setPayload] = useState<LPTokens | undefined>();

    const getLPTokenData = async () => {
        setLoading(true);
        try {
            const res = await axios.post(subgraphEndpoint,
                {
                    headers: { "Content-Type": "application/json" },
                    query: graphQuery
                }
            );
            setStatus(res.status);
            setResponse(res);
            setPayload(res.data);
        } catch (error) {
            setError(error);
        }
        setLoading(false);
    }

    useMemo(() => {
        getLPTokenData();
    }, [])

    return { status, loading, error, response, payload };
}

使用该Hook的组件:

const Dashboard: React.FC = () => {
    const { account } = useActiveWeb3React();

    const { status: status1, loading: loading1, error: error1, response: response1, payload: payload1 } = useAllLPTokens();
    console.log(payload1);
    // ...
}

我不确定为什么在Hook中使用useMemo时,当我检查浏览器控制台时,它会无限触发。但当我使用useEffect时,它不会无限触发。我没有为useMemo指定任何依赖项,我假设它只会在调用时触发一次。这是什么原因呢?

(请注意,我已经去除了代码部分,只返回翻译好的内容,如您所要求。)

英文:

I have a custom react hook that I wrote to query data from a subgraph endpoint. It simply returns an array of objects.

const useAllLPTokens = (): GraphQLResponse&lt;LPTokens&gt; =&gt; {
    const [status, setStatus] = useState&lt;number&gt;(0);
    const [loading, setLoading] = useState&lt;boolean&gt;(false);
    const [error, setError] = useState&lt;any&gt;();
    const [response, setResponse] = useState&lt;any&gt;();
    const [payload, setPayload] = useState&lt;LPTokens | undefined&gt;();

    const getLPTokenData = async () =&gt; {
        setLoading(true);
        try {
            const res = await axios.post(subgraphEndpoint,
                {
                    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },
                    query: graphQuery
                }
            );
            setStatus(res.status);
            setResponse(res)
            setPayload(res.data)
        } catch (error) {
            setError(error)
        }
        setLoading(false);
    }

    useMemo(() =&gt; {
        getLPTokenData();
    }, [])

    return { status, loading, error, response, payload }
}

Component where it is used:

const Dashboard: React.FC = () =&gt; {
    const { account } = useActiveWeb3React();

    const { status: status1, loading: loading1, error: error1, response: response1, payload: payload1 } = useAllLPTokens();
    console.log(payload1);
    ...

I'm not sure why when I use useMemo in the hook, it fires endlessly when I check the browser console. However when I use useEffect it doesn't. I didnt include any dependency for useMemo and I assumed it will only fire once when it is called. What is the reason for this?

答案1

得分: 2

使用useMemo()而没有依赖数组将在每次渲染时计算该值。

请参考此链接:

https://reactjs.org/docs/hooks-reference.html#usememo

如果没有提供数组,将在每次渲染时计算新值。

英文:

Using useMemo() without the dependencies array will calculate the value on every render.

See this link for reference

https://reactjs.org/docs/hooks-reference.html#usememo

> If no array is provided, a new value will be computed on every render.

huangapple
  • 本文由 发表于 2023年2月16日 18:07:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定