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

问题描述

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

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,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,但它带来的问题比解决的要多。

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)