fetchMore导致页面意外重新渲染

时间:2020-10-20 07:32:48

标签: reactjs apollo react-apollo apollo-client

我有一个无限的滚动列表。我最近更新到最新的Apollo客户端,并注意到无限滚动不再有效。

进一步调查。我注意到,当我使用递增的跳过调用fetchmore时,它将导致整个页面重新呈现。有什么想法吗?

查询:

   const {
      data,
      loading: queryLoading,
      fetchMore,
      error,
      networkStatus
    } = useQuery(SEARCH_PROFILES, {
      variables: { ...searchParams, skip: skip.current },
      fetchPolicy: "cache-first",
      notifyOnNetworkStatusChange: true
    });

FetchMore

 const fetchData = () => {
      ErrorHandler.setBreadcrumb("Fetch more profiles");
      skip.current =
        skip.current + parseInt(process.env.REACT_APP_SEARCHPROS_LIMIT);
      const intLimit = parseInt(process.env.REACT_APP_SEARCHPROS_LIMIT);

      if (hasMore.current) {
        fetchMore({
          variables: {
            searchType,
            long,
            lat,
            distance,
            ageRange,
            interestedIn,
            skip: skip.current,
            limit: intLimit,
            isMobile: sessionStorage.getItem("isMobile")
          },
          updateQuery: (previousResult, { fetchMoreResult }) => {
            if (!fetchMoreResult) {
              hasMore.current = false;
              return previousResult;
            } else if (
              fetchMoreResult.searchProfiles.profiles.length < intLimit
            ) {
              hasMore.current = false;
            }
            const newData = produce(previousResult, (draftState) => {
              if (draftState.searchProfiles.profiles) {
                draftState.searchProfiles.profiles.push(
                  ...fetchMoreResult.searchProfiles.profiles
                );
              } else {
                draftState.searchProfiles.profiles =
                  fetchMoreResult.searchProfiles.profiles;
              }
            });

            return newData;
          }
        });
      }
    };

1 个答案:

答案 0 :(得分:1)

嗯,根据您的解释,重新渲染是必要的,因为滚动时您正在加载新内容, 但是对于整个页面来说,不被重新渲染是我们在这里所关心的...下面的提示可能会有所帮助。

  1. 将需要滚动获取数据的页面部分提取到单独的组件中,因为它将是唯一需要重新呈现的组件
  2. React.memo()包装提取的组件,以便在数据无变化时不会重新呈现。
  3. 充分利用生命周期挂钩方法,它们是用于管理在何处或如何进行重新渲染的工具