React-Query Refetch与缓存问题:表单字段重置及缓存复用异常
问题解决方案
问题1:同一Type下重复搜索相同关键词重复请求API
核心原因是react-query默认staleTime为0,即便查询键匹配,组件重渲染时也会判定数据过期并发起新请求;同时需确保查询键正确关联Type、缓存标识与输入值,保证相同上下文的查询能复用缓存。
解决步骤:
- 调整
useQuery的查询键,将Type纳入其中,实现不同Type下的缓存隔离,同一Type下相同输入值复用缓存:
const { data } = useQuery( [cacheKey, inputValue, type], // 加入type到查询键,确保上下文唯一 () => fetchData(inputValue, type), // 确保API请求携带type参数 { enabled: !!inputValue, staleTime: Infinity, // 设为永久不过期,或根据业务需求设置具体时长 cacheTime: Infinity, } );
- 配置
staleTime与cacheTime,避免重复请求已缓存的有效数据。若业务允许永久复用缓存,设置为Infinity;若需定期更新,设置对应毫秒值即可。
问题2:无结果时切换Type无法重置inputValue
原因是CacheAutocompleteField组件未实现受控模式,父组件无法直接控制输入框的值。需修改组件支持受控属性:
- 修改
CacheAutocompleteField组件,新增inputValue和onInputChange属性:
interface CacheAutocompleteFieldProps { cacheKey: string; fetchData: (input: string, type: string) => Promise<Option[]>; type: string; inputValue?: string; // 新增受控输入值属性 onInputChange?: (value: string) => void; // 新增输入变化回调 placeholder: string; } const CacheAutocompleteField = ({ cacheKey, fetchData, type, inputValue: propsInputValue, onInputChange, placeholder, }) => { const [localInputValue, setLocalInputValue] = useState(''); // 优先使用父组件传入的受控值,否则用本地状态 const inputValue = propsInputValue ?? localInputValue; const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { const value = event.target.value; onInputChange ? onInputChange(value) : setLocalInputValue(value); }; // 后续逻辑中,将原用到localInputValue的地方替换为inputValue // ...(其余原有逻辑保持不变) };
- 在父组件中维护Country和City的输入值状态,切换Type时直接重置这两个状态:
const App = () => { const [type, setType] = useState('A'); const [countryInput, setCountryInput] = useState(''); const [cityInput, setCityInput] = useState(''); const handleTypeChange = (newType: string) => { setType(newType); // 重置输入框值 setCountryInput(''); setCityInput(''); }; return ( <div> <select value={type} onChange={(e) => handleTypeChange(e.target.value)}> <option value="A">Type A</option> <option value="B">Type B</option> </select> <CacheAutocompleteField cacheKey="countries" fetchData={fetchCountries} type={type} inputValue={countryInput} onInputChange={setCountryInput} placeholder="Country" /> <CacheAutocompleteField cacheKey="cities" fetchData={fetchCities} type={type} inputValue={cityInput} onInputChange={setCityInput} placeholder="City" /> </div> ); };
修改后,切换Type时会强制重置Country和City的输入值,无论之前是否有选中结果;同时同一Type下相同搜索关键词会复用react-query缓存,避免重复API请求。
内容的提问来源于stack exchange,提问作者user21131539
相关产品推荐
相关产品推荐

