【问题标题】:FetchMore : Request executed twice every timeFetchMore : 请求每次执行两次
【发布时间】:2021-06-01 02:51:09
【问题描述】:

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

我在网站上的视觉行为正常。当我点击获取更多按钮时,添加了 10 个新的 cmets。

我的问题是请求每次执行两次。我不知道为什么。第一次,它使用光标值执行,第二次没有它。似乎每次 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
        }
      }
    }
  }
`;

【问题讨论】:

    标签: reactjs graphql apollo apollo-client


    【解决方案1】:

    添加

    nextFetchPolicy: "cache-first"
    

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

    这解决了我的问题。

    【讨论】:

    【解决方案2】:

    如果您担心它只会发出一个请求,但每次 useQuery 挂钩中的项目更改时,react 组件都会刷新但不会重新渲染。

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

    【讨论】:

    • 它确实提出了两个请求。我的后端被调用了 2 次,我在后端有 console.logs。
    【解决方案3】:

    你看到的第二个请求会不会只是因为 refetchOnWindowFocus,因为这种情况经常发生......

    【讨论】:

      猜你喜欢
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多