如何在SWR已获取数据后触发加载状态?解决刷新时isLoading无效问题
解决SWR mutate时加载状态不显示的问题
SWR的isLoading仅在首次数据请求阶段为true,调用mutate()重新获取数据时该状态不会更新,导致加载指示器无法触发。你可以通过以下两种方式解决:
方法1:手动维护刷新状态
自定义状态变量控制刷新时的加载状态,结合mutate()的Promise返回值更新状态:
import { useState } from 'react'; import useSWR from 'swr'; const fetcher = (...args) => fetch(...args).then(res => res.json()); function TableComponent() { // 自定义刷新状态 const [isRefreshing, setIsRefreshing] = useState(false); const { data: originalData, isLoading, mutate } = useSWR('fetch-table', fetcher); const handleRefresh = async () => { setIsRefreshing(true); try { // 等待mutate请求完成 await mutate(); } finally { // 请求结束后关闭加载状态 setIsRefreshing(false); } }; // 合并初始加载和刷新加载状态 const showLoading = isLoading || isRefreshing; return ( <div> <button onClick={handleRefresh}>刷新</button> {showLoading && <div>正在加载...</div>} {/* 你的表格组件 */} </div> ); }
这种方式完全可控,仅在点击刷新按钮时显示加载状态,不受SWR自动重新验证逻辑影响。
方法2:使用SWR自带的isValidating状态
SWR提供的isValidating状态会在任何数据验证/重新请求阶段变为true,包括调用mutate()的场景:
import useSWR from 'swr'; const fetcher = (...args) => fetch(...args).then(res => res.json()); function TableComponent() { const { data: originalData, isLoading, isValidating, mutate } = useSWR('fetch-table', fetcher); const handleRefresh = () => { mutate(); }; // 合并初始加载和重新验证的加载状态 const showLoading = isLoading || isValidating; return ( <div> <button onClick={handleRefresh}>刷新</button> {showLoading && <div>正在加载...</div>} {/* 你的表格组件 */} </div> ); }
注意:isValidating会在SWR自动触发的重新验证(如页面聚焦、定时刷新)时也变为true,若不需要这些场景显示加载状态,方法1更合适。
内容的提问来源于stack exchange,提问作者Jantoma21
相关产品推荐
相关产品推荐

