我遇到了以下问题,我正在尝试使用react-query tanstack来实现infiniteQuery,但是如果不对pageParam的数字类型进行额外检查,我就无法做到这一点。
你能告诉我如何在不影响文件结构的情况下简化这段代码吗
ApiClient.ts
import axios from "axios";
const apiClient = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com/'
})
class API<T> {
constructor(public endpoint: string) {
}
getAll = (pageParam: number) => {
return apiClient.get<T[]>(this.endpoint, {
params: {
_page: pageParam
}
}).then(res => res.data)
.catch(err => err)
}
}
export default API
todo-service.ts
import API from "../api-service/api-client.ts";
export interface Todo {
userId: number;
id: number;
title: string;
completed: boolean;
}
const UseTodoService = new API<Todo>('todos')
export default UseTodoService;
使用Todo钩子
import {useInfiniteQuery} from "@tanstack/react-query";
import {CACHE_KEY_TODO} from "../constants.ts";
import UseTodoService, {Todo} from "../http-service/todo-service.ts";
const UseTodo = () => {
return useInfiniteQuery<Todo[], Error>({
queryKey: CACHE_KEY_TODO,
queryFn: ({pageParam}) => {
if (typeof pageParam === 'number') return UseTodoService.getAll(pageParam);
else throw new Error("pageParam must be a number.");
},
getNextPageParam: (lastPage, allPages) =>
lastPage.length > 0 ? allPages.length + 1 : undefined,
initialPageParam: 1
})
}
export default UseTodo;
Todo 组件
import useTodo from "../hooks/useTodo.ts";
function TodoList() {
const {data, fetchNextPage } = useTodo()
return <>
<h1>TodoList</h1>
<ul className="list-group">
{data?.pages.map(todos => todos.map((todo, index) =>
<li className="list-group-item" key={index}>{todo.title}</li>))}
</ul>
<button onClick={() => fetchNextPage()} className="btn btn-primary mt-2">Fetch More</button>
</>
}
export default TodoList;
我期待有关如何重构此代码以使其更简洁且无需额外检查 pageParams 类型的帮助
queryFn: ({pageParam}) => {
if (typeof pageParam === 'number') return UseTodoService.getAll(pageParam);
else throw new Error("pageParam must be a number.");
},
pageParam
已输入为 number
。您可以删除额外的类型检查。
当您在 TypeScript 中定义具有特定类型的变量(例如
initialPageParam: 1
)时,TypeScript 会根据分配的值推断该变量的类型。在本例中,initialPageParam
被推断为 number
类型,因为您已为其分配了值 1。
pageParam
变量也是TPageParam
类型,我们可以根据您的使用情况推断出它是 number 的类型别名。因此,您不需要对 pageParam
执行 typeof 检查,因为 TypeScript 已经知道它是 number