Mar*_*tzy 10 javascript reactjs react-query
我想通过以下方式实现这个场景react-query:
我的组件获取一个 API,并且应该在客户端的互联网断开连接时尝试一次,并且如果重新连接互联网则永远不会重新获取...并且在 3 秒后如果重试不成功,应该显示错误并带有用于重试请求的按钮。
const URL = 'https://randomuser.me/api/?results=5&inc=name';
const Example = () => {
const { error, data, isLoading, refetch } = useQuery('test', () =>
fetch(URL).then(response => response.json()).then(data => data.results), {
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: 1,
retryDelay: 3000
});
if (isLoading) return <span>Loading...</span>
if (error) return <span>Error: {error.message} <button onClick={refetch}>retry</button></span>
return (
<div>
<h1>Length: {data ? console.log(data.length) : null}</h1>
<button onClick={refetch}>Refetch</button>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
考虑到上面的代码,我设置refetchOnReconnect: false为在连接互联网后禁用重新获取,retry: 1设置一次尝试并retryDelay: 3000设置重试时间限制。
但是当我在 DevTools 中使用 Throttling -> 离线时,单击按钮后仅显示最后的结果,并且 3 秒后不显示错误和重试按钮...
那么,有什么办法可以处理这个功能吗?
小智 2
React-query使用缓存中的数据时,您应该通过调用以下函数使查询无效以再次获取数据invalidateQueries:
onst URL = 'https://randomuser.me/api/?results=5&inc=name'
const Example = () => {
// Get QueryClient from the context
const queryClient = useQueryClient()
const { error, data, isLoading, refetch } = useQuery(
'test',
() =>
fetch(URL)
.then(response => response.json())
.then(data => data.results),
{
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: 1,
retryDelay: 3000
}
)
const buttonClickHandler = () => queryClient.invalidateQueries('test') // <=== invalidate the cache
if (isLoading) return <span>Loading...</span>
if (error)
return (
<span>
Error: {error.message} <button onClick={refetch}>retry</button>
</span>
)
return (
<div>
<h1>Length: {data ? console.log(data.length) : null}</h1>
<button onClick={buttonClickHandler}>Refetch</button>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18326 次 |
| 最近记录: |