在反应中从另一个钩子调用钩子 [英] Call hook from another hook in react

查看:19
本文介绍了在反应中从另一个钩子调用钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对做出反应并试图简化一些开发工作还很陌生.

I'm quite new to react and trying to ease some development.

我有这个自定义钩子 useApi.

I'm having this custom hook 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
    }
};

我想从另一个组件中调用它,就像在这个片段中一样.

I'd like to call it from within another component like in this snippet.

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

但是 react 告诉我我缺少对 listPets
的依赖React Hook useEffect 缺少依赖项:'listPets'.要么包括它要么删除依赖数组

However react is telling me that I'm missing the dependency on listPets
React Hook useEffect has a missing dependency: 'listPets'. Either include it or remove the dependency array

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

I've tried to include listPets as a dependency but that leads to repeatable call to backend service. What would be the best way to rewrite the call to useApi hook?

谢谢

推荐答案

更改组件的 useEffect:

Change component's useEffect:

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

然后尝试像这样使用 useCallBack 钩子包装 listPets 函数:

And then try to wrap listPets function with useCallBack hook like this:

const showPetById = useCallback((petId) => {
    setIsLoading(true);
    return petsApi.showPetById(petId, {
        headers: {
            Authorization: `Bearer ${keycloak.token}`
        }
    }).finally(() => setIsLoading(false));
},[petsApi]);

这篇关于在反应中从另一个钩子调用钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆