如何在重复3次后停止refetchInterval反应查询(useQuries)?

Sab*_*med 3 javascript react-native react-query

这里我使用 React Query 来获取数据。我在 useQuries refetchInterval 中使用了 3000 毫秒,所以每 3 秒就会重新获取数据。因此,当我显示数据时,它会随着我们重新获取数据而自动更改。但就我而言,我不想重新获取数据超过 3 次,假设我只想使用 {refetchInterval : 3000} 3 次,然后它将停止重新获取数据。

有什么办法可以做到这一点吗?我怎样才能使用 refetchInterval 选项修复它 3 次。ecah time 它将在 3 秒后重新获取,onec 它重新获取 3 次它将自动停止,并且不再有 reftech 将工作。

请帮我解决这个问题并在 3 次后中断 refetchInterval。感谢您的提前尝试!

  const fetchData = () => {
            const rA=  devices?.map(async (id) => {
                const info = await axios.get(`https://www.roads.com/road/api/roadControl/${id}`, myHeaders).then((res) => {
                    return res.data;
                })
                return info
                
            })
            
            return rA;
        };
    
        const { data } = useQuery("post", fetchData,
            { refetchInterval: 3000 });
Run Code Online (Sandbox Code Playgroud)

Kon*_*owy 10

这应该有效

const countRef = useRef(0)
const { data } = useQuery("post", () => {
  countRef.current += 1
  return fetchData()
}, { refetchInterval: () => countRef.current < 3 ? 3000 : false });
Run Code Online (Sandbox Code Playgroud)

  • 使用“refetchInterval”作为函数的答案是正确的 - 我只是想指出 ref 可能是不必要的,因为该函数获取了“query”传递,并且查询包含“query.state.dataUpdateCount”,您可以检查是否大于 3。 (7认同)
  • 扩展 @TkDodo 注释: `refetchInterval: (_data, query) =&gt; (query.state.dataUpdateCount &gt; 3: 3000 : false)` (3认同)