我是一个刚开始做出反应并试图简化一些开发的人。
我有这个自定义挂钩useApi
。
import {useState} from "react";
import {PetsApiFactory} from "petstore-axios-api"
import {useKeycloak} from "@react-keycloak/web";
const petsApi = new PetsApiFactory({}, `${process.env.REACT_APP_BASE_URL}`);
export const useApi = () => {
const [isLoading, setIsLoading] = useState(false);
const {keycloak} = useKeycloak();
const createPets = (requestData) => {
setIsLoading(true);
return petsApi.createPets(requestData, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
};
const listPets = (limit = undefined) => {
setIsLoading(false);
return petsApi.listPets(limit, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
};
const showPetById = (petId) => {
setIsLoading(true);
return petsApi.showPetById(petId, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
};
return {
createPets,
listPets,
showPetById,
isLoading
}
};
我想从另一个组件中调用它,就像这个片段中一样。
useEffect(() => {
listPets()
.then(result => setPetsData(result.data))
.catch(console.log)
}, []);
然而react告诉我,我缺少对listPets
React Hook useEffect has a missing dependency: 'listPets'. Either include it or remove the dependency array
的依赖
我曾尝试将listPets
作为一个依赖项,但这导致了对后端服务的可重复调用。重写对useApi
钩子的调用的最佳方法是什么?
感谢
更改组件的使用效果:
useEffect(() => {
listPets()
.then(result => setPetsData(result.data))
.catch(console.log)
}, [listPets]);
然后尝试用useCallBack钩子包装listPets函数,如下所示:
const showPetById = useCallback((petId) => {
setIsLoading(true);
return petsApi.showPetById(petId, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
},[petsApi]);
您忘记了将listPets添加到useEffect 中
useEffect(() => {
listPets()
.then(result => setPetsData(result.data))
.catch(console.log)
}, [listPets]);