lol*_*.io 1 apollo reactjs graphql apollo-client
我正在尝试在评论部分实现分页。
我在网站上有正常的视觉行为。当我单击“获取更多”按钮时,会添加 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>
);
};
Run Code Online (Sandbox Code Playgroud)
询问 :
const getMoreCommentsQuery = gql`
query($id: ID, $cursor: ID) {
event(id: $id) {
id
comments(cursor: $cursor) {
id
text
author {
id
displayName
photoURL
}
}
}
}
`;
Run Code Online (Sandbox Code Playgroud)
添加
nextFetchPolicy: "cache-first"
Run Code Online (Sandbox Code Playgroud)
useQuery当组件重新呈现时,钩子可以防止进行服务器调用。
这解决了我的问题。
| 归档时间: |
|
| 查看次数: |
658 次 |
| 最近记录: |