📌  相关文章
📜  用于 React 的 useFetch 自定义钩子 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:02.853000             🧑  作者: Mango

代码示例1
import { useEffect, useState } from 'react';

const useFetch = (url) => {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const abortCont = new AbortController();

        fetch(url, { signal: abortCont.signal })
            .then((res) => {
                if (!res.ok) {
                    throw Error('Could not fetch the data for that resource');
                }
                return res.json();
            })
            .then((data) => {
                setData(data);
                setIsLoading(false);
                setError(null);
            })
            .catch((err) => {
                if (err.name === 'AbortError') {
                    console.log('Fetch aborted');
                } else {
                    setError(err.message);
                    setIsLoading(false);
                }
            });
        return () => abortCont.abort();
    }, [url]);
    return { data, isLoading, error };
};