@bjornagh/ use- fatch (英语)
方便使用的回放钩 fetch 请求.
特征
- 1️⃣ Dedupes请求完成到同一端点. 对同一终点只提出一项请求.
- QQ 响应以提高速度并减少请求量 .
- 如果 URL 更改, 则自动提出新请求 .
- * 规模小,只有两个依赖:
react财务报告和审定财务报表fetch-dedupe。 。 。 .
安装
npm install @bjornagh/use-fetch
# if yarn
yarn add @bjornagh/use-fetch
使用量
- 创建缓存( 新地图( ))并渲染
FetchProvider在您的应用程序的顶端.
import { FetchProvider } from "@bjornagh/use-fetch";
const cache = new Map();
ReactDOM.render(
<FetchProvider cache={cache}>
<App />
</FetchProvider>,
document.getElementById("container")
);
- 使用
useFetch在组件中
import React from "react";
import { useFetch } from "@bjornagh/use-fetch";
function MyComponent() {
const { data, fetching } = useFetch({
url: "https://jsonplaceholder.typicode.com/todos"
});
return (
<div>
{fetching && "Loading..."}
{data && data.map(x => <div key={x.id}>{x.title}</div>)}
</div>
);
}
更多例子见示例部分 示例一节 。 。 。 .
API 密码
useFetch 接受支持以下属性的对象
| 密钥 | 默认值 | 说明 |
|---|---|---|
| url 密码 | 要发送请求的 URL | |
| 方法 | 获取 | HTTP 方法 |
| 懒惰 | 无效 | 懒惰模式决定一个请求是否应在挂载上完成,以及请求参数何时变化(如URL)或不变化. 当挂载时只启动 GET 请求时, 例如如果 URL 更改 。 若为 true 这适用于所有请求,不论HTTP方法如何。 若为 false,请求只通过手动启动 doFetch,返回函数 useFetch |
| 输入 | {} | 见 https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorker GlobalScope/fetch (中文(简体) ) init 支持键的参数 |
| 脱发选项 | {} | 见 https://github.com/jamesplease/fetch-dedupe#user-content-api 页面存档备份,存于互联网档案馆 dedupeOptions 支持键的参数 |
| 缓存响应 | 已读请求为真, 已写为假 | 缓存响应与否 |
| 请求键 | 无效 | requestKey被用作缓存密钥并预防重复请求. 如果无一被传递,则自动生成. |
| 缓存政策 | 无效 | 藏匿战略 |
| 刷新“ Dotch” | 函数 | 默认 doFetch 方法为纪念( 通过 useCallback),使用请求(url+方法+body). 如果您得到一个 stale doFatch , 请使用它来覆盖 。 它收到一个参数,即默认请求密钥. 譬如说. requestKey => requestKey + 'something' |
| 错误 | 函数 | 获取失败时称为回调函数 。 接收 a Response 成为唯一的争论。 默认要控制台的日志 |
| 成功时 | 函数 | 一个调用函数,在每次获取成功时都称为调用函数 。 接收获取 Response 成为唯一的争论。 默认不做( 无) |
返回值
| 密钥 | 类型 | 说明 |
|---|---|---|
| 回应 | Response | Response |
| 数据 | * 联合国 | 请求数据回复 |
| 获取 | 布尔 | 请求是否在飞行中 |
| 错误 | Response | 任何错误来自 fetch |
| 请求键 | 字符串 | 用作缓存密钥并用于防止重复请求 |
| ưμ㼯A | 函数 | 手动启动请求的函数 。 还有一个论点: init,发送对象 fetch。见 https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorker GlobalScope/fetch (中文(简体) ) (单位:千美元)init 参数。 返回一个承诺. |
注:请求 Content-type 设置为 application/json 将自动拥有他们的身体
已字符串( e)JSON.stringify(中文(简体) )
cachePolicy
cache-first- 如果可用,在缓存中使用响应。 如果不是,则会提出请求.cache-and-network- 在可得到的缓存中使用响应,但也总是在背景中提出新的请求,以刷新任何陈旧的数据.exact-cache-and-network- 类似cache-and-network,但只有在请求相同时才会显示缓存响应(url+方法+body).network-only- 忽略缓存,总是提出请求.
读取默认请求( GET、 选项、 头) cache-first。 。 。 .
写入请求( POST, DELETE, PUT, PATCH) 默认为 network-only。 。 。 .
实例
POST 请求及随后更新视图
function Demo() {
// Fetch list of posts
const posts = useFetch({
url: "https://jsonplaceholder.typicode.com/posts"
});
// Prepare create request
// This will not be initiated until you call `createPost.doFetch()`
const createPost = useFetch({
url: "https://jsonplaceholder.typicode.com/posts",
method: "POST",
init: {
headers: {
"Content-type": "application/json"
}
}
});
return (
<div>
<button
onClick={() =>
createPost
.doFetch({
body: {
title: "foo",
body: "bar",
userId: 1
}
})
.then(response => {
if (response.ok) {
// POST request was successful, refetch list of posts
posts.doFetch();
} else {
// Do something with error response
}
})
}
disabled={createPost.fetching}
>
Create post
</button>
{!posts.data && posts.fetching && "Loading..."}
{posts.data && posts.data.map(x => <h2 key={x.id}>{x.title}</h2>)}
</div>
);
}
延迟使用 lazy 道具
设置 lazy 参数改为 true 告诉 useFetch 不在挂载时或何时开始请求
请求参数改变.
你可以随时改变这个 此功能有用的一个常见模式是您需要时 用户在启动请求前应用一些过滤器.
以下是一个请求被延迟到搜索输入至少包含两个字符的例子.
function LazyDemo() {
const [searchFilter, setSearchFilter] = useState("");
const posts = useFetch({
url: `/posts?search=${searchFilter}`,
lazy: searchFilter.length < 2 // Request is lazy as long as the input has less than two characters
});
return (
<div>
<input onChange={event => setSearchFilter(event.target.value)} />
{posts.data && posts.data.map(x => <div key={x.id}>{x.title}</div>)}
</div>
);
}
如何设置基准 URL、默认信头等
创建自定义取钩 。 例如:
import { useFetch } from "@bjornagh/use-fetch";
function useCustomUseFetch({ url, init = {}, ...rest }) {
// Prefix URL with API root
const apiRoot = "https://my-api-url.com/";
const finalUrl = `${apiRoot}${url}`;
// Set a default header
const finalHeaders = { ...init.headers };
finalHeaders["Content-type"] = "application/json";
// Ensure headers are sent to fetch
init.headers = finalHeaders;
return useFetch({ url: finalUrl, init, ...rest });
}
使用自定义的钩子, 您也可以设置一个默认错误处理器, 例如显示一个祝词 .
贷项
这个图书馆深受优秀的React图书馆的启发 响应请求