为什么我的useCallback函数在我的useEffect中导致无限循环?



我有一个名为getContentfulProjectById的函数。它实际上是通过传递给它的id获取一个有内容的项目。它存在于services/useContentful钩子中。

import { createClient } from "contentful";
import {
setContentfulProjects,
setContentfulStaff,
setSelectedProject,
} from "store/actions/contentfulActions";
import { store } from "store/store";
const useContentful = () => {
const getContentfulProjects = async () => {
try {
const entries = await client.getEntries({
content_type: "projects",
select: "fields",
order: "fields.name",
});
store.dispatch(setContentfulProjects(entries));
} catch (error) {
console.log(`Error Fetching Programs:${error}`);
}
};
const getContentfulStaff = async () => {
try {
const entries = await client.getEntries({
content_type: "staff",
select: "fields",
order: "fields.staffId",
});
store.dispatch(setContentfulStaff(entries));
} catch (error) {
console.log(`Error Fetching Programs:${error}`);
}
};
const getContentfulProjectById = useCallback(async (projectId) => {
try {
const entries = await client.getEntries({
content_type: 'projects',
'fields.projectId': projectId,
});
store.dispatch(setSelectedProject(entries));
} catch (error) {
console.log(`Error Fetching Programs:${error}`);
}
}, []);
return {
getContentfulProjects,
getContentfulStaff,
getContentfulProjectById,
};
};
export default useContentful;

组件使用钩子useParams来获取projectId参数,将其传递给我通过名为queryForProject的useCallback函数调用的函数,并将函数和useParams的结果传递给依赖数组。然后在useEffect中调用这个函数。我将queryForProject作为一个依赖项传递给useEffect,它导致了一个无限循环。如果我要从依赖数组中删除该函数,我不会看到循环,但会看到需要将该函数作为依赖传递的警告。

const { projectId } = useParams();
const { getContentfulProjectById } = useContentful();
const queryForProject = useCallback(async () => {
await getContentfulProjectById(projectId);
setIsLoading(false);
}, [getContentfulProjectById, projectId]);
useEffect(() => {
queryForProject();
}, [queryForProject]);

如果queryForProject函数应该只运行一次,下面的代码应该足够了!

useEffect(() => {
async function queryForProject() {
await getContentfulProjectById(projectId);
setIsLoading(false);
}
queryForProject();
}, [getContentfulProjectById])

你可以尝试包装getContentfulProjectById函数与useCallback?

const getContentfulProjectById = useCallback(async (projectId) => {
try {
const entries = await client.getEntries({
content_type: 'projects',
'fields.projectId': projectId,
});
store.dispatch(setSelectedProject(entries));
} catch (error) {
console.log(`Error Fetching Programs:${error}`);
}
}, []);

相关内容

  • 没有找到相关文章

最新更新