RTK Query
RTK Query 是 Redux Toolkit 强大的数据获取与缓存层。它无需编写异步 action 创建器,并自动管理加载状态、缓存和数据同步。
基础客户端配置
所有 RTK Query 端点都扩展自同一个基础客户端实例。
基础查询设置
// src/services/baseQuery.ts
import { fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import type { RootState } from '@/app/store';
export const baseQuery = fetchBaseQuery({
baseUrl: process.env.NEXT_PUBLIC_API_URL, // 例如:https://api.decentraland.org
prepareHeaders: (headers, { getState }) => {
const state = getState() as RootState;
// 添加认证令牌
const token = state.user.session?.authToken;
if (token) {
headers.set('authorization', `Bearer ${token}`);
}
// 为 web3 上下文添加链 ID
const chainId = state.user.chainId;
if (chainId) {
headers.set('x-chain-id', String(chainId));
}
// 标准请求头
headers.set('accept', 'application/json');
headers.set('content-type', 'application/json');
return headers;
},
credentials: 'omit', // 如果后端需要 cookie,则使用 'include'
});客户端实例
标签约定
标签用于缓存失效和同步。请遵循以下约定:
标签命名
资源类型
查询标签
变更失效
集合
'Parcels' (复数)
'Parcels'
单个实体
{type: 'Parcels', id: '123'}
{type: 'Parcels', id: '123'}
列表 + 详情
['Parcels', {type: 'Parcels', id}]
['Parcels'] 或特定 id
标签示例
创建端点
端点应与其功能一起放在 feature.client.ts 文件中。
查询端点(读取)
变更端点(写入)
乐观更新
使用 onQueryStarted 用于乐观 UI 更新,并在失败时自动回滚。
高级查询选项
轮询
跳过查询
惰性查询
转换响应
自定义序列化
对于分页或搜索,自定义缓存键序列化:
错误处理
自定义错误处理
在组件中的用法:
缓存管理
手动更新缓存
使缓存失效
重置客户端状态
预取数据
最佳实践
1. 使用描述性的端点名称
2. 提供全面的标签
3. 处理加载和错误状态
4. 使用类型守卫
下一步
最后更新于