我制作了一个自定义钩子,用于获取新闻 API 并返回用于加载、错误和数据的处理程序(受到 Apollo Client 的启发)。问题是,当使用它时,即使依赖项数组中的项目没有改变,它也会无限地自行触发。这就是我的实现方式:
钩子:
const useSearch = (query: string, sources: string[]) => {
const [response, setResponse] = useState<State>({
data: null,
loading: true,
error: null,
});
useEffect(() => {
newsapi
.getEverything({
q: query,
pageSize: 1,
sources: sources,
})
.then((data) => {
setResponse({ data, loading: false, error: null });
})
.catch((e) => {
setResponse({ data: null, loading: false, error: e });
});
}, [query, sources]);
return response;
};
用法:
const { loading, error, data } = useSearch("Donald", ["bbc-news"]);
我超出了 API 的每日费率:
我究竟做错了什么?
拉风的咖菲猫
相关分类