如何解决FetchMore :请求每次执行两次
我在网站上有正常的视觉行为。当我点击“获取更多”按钮时,会添加 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
}
}
}
}
`;
解决方法
添加
nextFetchPolicy: "cache-first"
到 useQuery
钩子可防止在组件重新呈现时进行服务器调用。
这解决了我的问题。
,如果您担心,它只会发出一个请求,但是每次 useQuery 钩子中的项目更改时,react 组件都会刷新但不会重新渲染。
例如它会在加载更改时刷新组件,使其看起来像是发送了多个请求。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。