我有一个NextJs程序和一个我在我的网站上使用的函数useAsync。由于某种原因,该函数每次被调用时都会运行两次。我认为这与useEffect调用useAsyncInternal有关,但我不确定。
下面是我的useAsync.tsx:
import { useCallback, useEffect, useState } from "react";
import useUser from "./useUser";
export const useAsync = (func: Function, dependencies = [], requireAuth = true) => {
const { execute, ...state } = useAsyncInternal(func, dependencies, true);
const user = useUser();
useEffect(() => {
if (requireAuth) {
if (user.id) execute();
} else {
execute();
}
}, [execute, user.id]);
return state;
}
const useAsyncInternal = (func: Function, dependencies = [], initialLoading = false) => {
const [loading, setLoading] = useState(initialLoading);
const [error, setError] = useState<any>();
const [data, setData] = useState<any>();
const execute = useCallback((...params: any[]) => {
setLoading(true);
return func(...params).then((data: any) => {
setData(data);
setError(undefined);
return data;
}).catch((error: any) => {
setData(undefined);
setError(error);
return Promise.reject(error);
}).finally(() => {
setLoading(false);
});
}, dependencies);
return { loading, error, data, execute }
}
下面是一个调用JSX的useAsync insde的示例:
const { loading, error, data } = useAsync(myCommunities);
下面是myCommunities函数,以防万一:
export const myCommunities = () => {
return request.get("/communities/my");
};
1条答案
按热度按时间jvlzgdj91#
可以使用
useMemo
由于依赖关系的变化,useEffect钩子可能被调用了两次。为了防止这种情况,您可以尝试将useAsyncInternal函数 Package 在useMemo钩子中,以确保它只被调用一次。