FetchMore:每次执行两次请求



我正在尝试在评论部分实现分页。

我在网站上的视觉行为正常。当我点击"获取更多"按钮时,会添加10条新评论。

我的问题是请求每次执行两次。我也不知道为什么。第一次使用游标值执行,第二次不使用游标值。似乎useQuery钩子是在每次fetchMore之后执行的。

任何帮助都会很感激。谢谢!

组件:

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
}
}
}
}
`;

添加

nextFetchPolicy: "cache-first"

useQuery钩子,防止在组件重新呈现时进行服务器调用。

这就解决了我的问题。

可能是你看到的第二个请求只是因为refetchOnWindowFocus,因为这种情况经常发生…

我有一个类似的问题,我通过将fetchPolicy改为network-only来解决它。

请注意,如果你在@apollo/client v3.5.x遇到这个问题,有一个与此相关的bug从v3.6.0+修复。在我的例子中,这个提交解决了重复执行问题。

如果你担心的话,它只会发出一个请求,但是每次useQuery钩子中的项发生变化时,react组件都会刷新而不是渲染。

例如,它会在加载更改时刷新组件,使其看起来像是发送了多个请求。

最新更新