从另一个钩子中调用钩子

时间:2020-03-17 12:47:08

标签: reactjs react-hooks

我很新来做出反应并试图缓解一些发展。

我有这个自定义钩子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)
}, []);

但是反应告诉我我缺少对listPets的依赖
React Hook useEffect has a missing dependency: 'listPets'. Either include it or remove the dependency array

我尝试将listPets包含为依赖项,但这导致可重复调用后端服务。将调用重写为useApi挂钩的最佳方法是什么?

谢谢

2 个答案:

答案 0 :(得分:1)

更改组件的useEffect:

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

答案 1 :(得分:0)

您忘记将listPets添加到useEffect

useEffect(() => {
listPets()
    .then(result => setPetsData(result.data))
    .catch(console.log)
}, [listPets]);