我的问题是由于某种原因分页不起作用,很可能是因为该文件中存在=未定义
import { FieldPolicy } from "@apollo/client/cache/inmemory/policies";
import unionBy from "lodash.unionby";
type KeyArgs = FieldPolicy<string>["keyArgs"];
export const cursorPagination = (
keyArgs: KeyArgs = ["afterCursor"],
unionByField = "__ref"
): FieldPolicy => ({
keyArgs,
merge(existing, incoming, { args }) {
const incomingResult = incoming ? incoming.data : [];
console.log("Incoming", incomingResult);
const existingResult = existing ? existing.data : [];
console.log("Existing", existingResult);
const hasNextCursor = Boolean(args?.pagination?.afterCursor);
if (hasNextCursor) {
const resultPagination = unionBy(
existingResult,
incomingResult,
unionByField
);
return {
...incoming,
results: resultPagination,
};
}
return incoming;
},
});
试图理解为什么会发生这种情况,我回到了我的请求,其操作如下
export const usePaginationPosts = () => {
const [getPaginatedPosts, { data, fetchMore }] = usepostsLazyQuery({
fetchPolicy: "cache-and-network",
});
const [afterCursor, setAfterCursor] =
(useState < string) | null | (undefined > null);
const [isLoading, setIsLoading] = useState(false);
const getPosts = useCallback(async () => {
setIsLoading(true);
try {
const response = await getPaginatedPosts({
variables: {
input: { limit: 10, afterCursor: null, type: PostFilterType.New },
},
});
setAfterCursor(response.data?.posts.pageInfo?.afterCursor);
console.log(
"response.data?.posts.pageInfo?.afterCursor",
response.data?.posts.pageInfo?.afterCursor
);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
getPosts();
}, [getPosts]);
const getMorePosts = useCallback(async () => {
if (afterCursor) {
const response = await fetchMore({
variables: {
input: { limit: 10, afterCursor, type: PostFilterType.New },
},
});
setAfterCursor(response.data?.posts.pageInfo?.afterCursor);
}
console.log(afterCursor);
}, []);
return { isLoading, getPosts, getMorePosts, data };
};
我的理论是问题出在 afterCursor 以防万一,这是我的缓存选项:
export const cacheOption: InMemoryCacheConfig = {
typePolicies: {
Query: {
fields: {
posts: defaultCursorPagination,
userMe: defaultCursorPagination,
},
},
},
};
同时查询请求:
query posts($input: FindPostsRequest!) {
posts(input: $input) {
data {
author {
firstName
lastName
avatarUrl
}
createdAt
description
id
isLiked
likesCount
mediaUrl
title
}
pageInfo {
afterCursor
count
perPage
}
}
}
我将不胜感激任何帮助
我认为你在这里使用了
keyArgs
“错误的方式”。
keyArgs
的要点是“如果这个参数不同,则基础数据不属于一起”。
因此,按照您使用它的方式,每个不同的
afterCursor
将位于不同的缓存条目中,并且事物永远不会合并在一起。
您可以将类似
filters
的内容放入 keyArgs
中,以防止具有不同过滤器的列表不会最终出现在同一个缓存条目中。