轮询 `useQuery` 会导致 React 组件中不必要的重新渲染

时间:2021-04-12 11:57:54

标签: reactjs graphql react-hooks apollo-client react-apollo-hooks

我有一个看起来像这样的钩子

export const useThing = id => {
    const { stopPolling, startPolling, ...result } = useQuery(GET_THING, {
        fetchPolicy: 'cache-and-network',
        variables: { id },
        skip: !id
    });

    return {
        startPolling,
        stopPolling,
        thing: result.data.thing,
        loading: result.loading,
        error: result.error
    };
}

然后在我的组件中我正在做这样的事情;

const {loading, error, thing, startPolling, stopPolling} = useThing(id);

// this is passed as a prop to a childComponent
const onUpdateThing = ()=> {
   setShowInfoMessage(true);
   startPolling(5000);
}

const verficationStatus = thing?.things[0]?.verificationStatus || 'PENDING';
useEffect(()=> {
   if(verficationStatus === 'FAILED' || verificationStatus === 'SUCCESS') {
   stopPolling();
 }
}, [verificationStatus])

我正在使用 startPollingstartPolling 函数动态轮询查询。这种方法的问题在于,每当我开始轮询时,假设间隔为 3 秒,组件将每 3 秒重新渲染一次。我希望组件仅在服务器发送更新的响应时呈现。 以下是我尝试调试的一些内容;

  • 我尝试使用 React Dev Tools 分析组件,它显示 hooks changed 作为重新渲染的原因。
  • 我在我的组件中使用了多个 useEffect 所以我的下一个想法 是为了检查是否有任何 useEffect 导致重新渲染。我尝试在 useEffect 调用中添加和删除每个依赖项,但似乎没有帮助。
  • 我也不存储状态中返回的任何值。
  • 子组件调用 mutation
  • 我也尝试过使用 React.memo,但它带来的问题比解决的要多。

对于可能导致问题的原因的任何想法将不胜感激。

0 个答案:

没有答案