我正在尝试在评论部分实现分页。
我在网站上有正常的视觉行为。当我点击“获取更多”按钮时,会添加 10 条新评论。
我的问题是请求每次执行两次。我不知道为什么。第一次,它使用游标值执行,第二次没有它。似乎每次 fetchMore 之后都会执行 useQuery 钩子。
任何帮助将不胜感激。谢谢!
组件:
export default ({ event }) => {
const { data: moreCommentsData, fetchMore } = useQuery(getMoreCommentsQuery, {
variables: {
id: event.id,
},
fetchPolicy: "cache-and-network",
});
const getMoreComments = () => {
const cursor =
moreCommentsData.event.comments[
moreCommentsData.event.comments.length - 1
];
fetchMore({
variables: {
id: event.id,
cursor: cursor.id,
},
updateQuery: (prev, { fetchMoreResult, ...rest }) => {
return {
...fetchMoreResult,
event: {
...fetchMoreResult.event,
comments: [
...prev.event.comments,
...fetchMoreResult.event.comments,
],
commentCount: fetchMoreResult.event.commentCount,
},
};
},
});
};
return (
<Container>
{moreCommentsData &&
moreCommentsData.event &&
moreCommentsData.event.comments
? moreCommentsData.event.comments.map((c) => c.text + " ")
: ""}
<Button content="Load More" basic onClick={() => getMoreComments()} />
</Container>
);
};
查询:
const getMoreCommentsQuery = gql`
query($id: ID, $cursor: ID) {
event(id: $id) {
id
comments(cursor: $cursor) {
id
text
author {
id
displayName
photoURL
}
}
}
}
`;
答案 0 :(得分:5)
添加
nextFetchPolicy: "cache-first"
到 useQuery
钩子可防止在组件重新呈现时进行服务器调用。
这解决了我的问题。
答案 1 :(得分:0)
如果您担心,它只会发出一个请求,但是每次 useQuery 钩子中的项目更改时,react 组件都会刷新但不会重新渲染。
例如它会在加载更改时刷新组件,使其看起来像是发送了多个请求。