简体   繁体   English

使用函数作为反应钩子?

[英]Use function as react hook?

I wanted to use a function as a react hook to wrap fetch requests to an API.我想使用一个函数作为反应钩子来包装对 API 的获取请求。

My current hook:我目前的钩子:

export function useAPI(url, options={}) {
    const [auth, setAuth] = useGlobal('auth');
    const [call, setCall] = useState(undefined);

    const apiFetch = async () => {
        const res = await fetch(url, {
            ...options,
        });
        if (!res.ok)
            throw await res.json();
        return await res.json();
    };

    function fetchFunction() {
        fetch(url, {
            ...options,
        });
    }

    useEffect(() => {
        // Only set function if undefined, to prevent setting unnecessarily
        if (call === undefined) {
            setCall(fetchFunction);
            //setCall(apiFetch);
        }

    }, [auth]);

    return call
}

That way, in a react function, I could do the following...这样,在反应功能中,我可以执行以下操作...

export default function LayoutDash(props) {
    const fetchData = useAPI('/api/groups/mine/'); // should return a function

    useEffect(() => {
        fetchData(); // call API on mount
    }, []);

    render(...stuff);
}

But it seems react isn't able to use functions in hooks like that.但似乎 react 无法在这样的钩子中使用函数。 If I set call to fetchFunction , it returns undefined .如果我将call设置为fetchFunction ,它将返回undefined If I set it to apiFetch , it executes and returns a promise instead of a function that I can call when I want to in the other component.如果我将它设置为apiFetch ,它会执行并返回一个承诺而不是一个我想在其他组件中调用时可以调用的函数。

I initially went for react hooks because I can't use useGlobal outside react components/hooks.我最初选择了 React 钩子,因为我不能在useGlobal组件/钩子之外使用useGlobal And I would need to have access to the reactn global variable auth to check if the access token is expired.而且我需要访问reactn全局变量auth以检查访问令牌是否已过期。

So what would be the best way to go about this?那么最好的方法是什么? The end goal is being able to pass (url, options) to a function that will be a wrapper to a fetch request.最终目标是能够将(url, options)传递给一个函数,该函数将成为获取请求的包装器。 (It checks if auth.access is expired, and if so, obtains a new access token first, then does the api call, otherwise it just does the API call). (它检查auth.access是否已过期,如果是,则首先获取新的访问令牌,然后进行 api 调用,否则仅进行 API 调用)。 If there's another way I should go about this other than react hooks, I'd like to know.如果除了反应钩子之外还有其他方法可以解决这个问题,我想知道。

Instead of putting your function into useState , consider using useCallback .与其将您的函数放入useStateuseState考虑使用useCallback Your code would look something like this:您的代码如下所示:

export function useAPI(url, options={}) {
    const [auth, setAuth] = useGlobal('auth');

    function fetchFunction() {
        fetch(url, {
            ...options,
        });
    }

    const call = useCallback(fetchFunction, [auth]);


    const apiFetch = async () => {
        const res = await fetch(url, {
            ...options,
        });
        if (!res.ok)
            throw await res.json();
        return await res.json();
    };

    return call
}

The returned function is recreated whenever auth changes, therefore somewhat mimicking what you tried to do with useEffect每当auth更改时都会重新创建返回的函数,因此有点模仿您尝试使用useEffect执行的useEffect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM