useFetch
信息
获取数据
1.实现
import { useState, useEffect } from "react";
const useFetch = (url = "", options = null) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
let isMounted = true;
setLoading(true);
fetch(url, options)
.then((res) => res.json())
.then((data) => {
if (isMounted) {
setData(data);
setError(null);
}
})
.catch((error) => {
if (isMounted) {
setError(error);
setData(null);
}
})
.finally(() => isMounted && setLoading(false));
return () => (isMounted = false);
}, [url, options]);
return { loading, error, data };
};
export default useFetch;
2.使用
import useFetch from "./useFetch";
const App = () => {
const {
loading,
error,
data = [],
} = useFetch("https://hn.algolia.com/api/v1/search?query=react");
if (error) return <p>Error!</p>;
if (loading) return <p>Loading...</p>;
return (
<div>
<ul>
{data?.hits?.map((item) => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
</div>
);
};