You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Query缓存复用及表单字段重置问题求助

问题解决方案

问题1:缓存未按Type字段区分,重复发起API请求

当前CacheAutocompleteField的react-query查询键仅包含cacheKey和inputValue,未关联表单的Type字段,导致不同Type下的相同搜索词共用同一缓存键,切换回原Type时无法复用对应缓存,重复触发API请求。

修复方案:

  1. 将当前表单的Type值加入查询键,确保不同Type下的相同搜索词生成独立缓存键
  2. 修改CacheAutocompleteField中的useQuery配置:
const { data } = useQuery(
  [cacheKey, inputValue, type], // 新增type到查询键,区分不同Type下的缓存
  () => queryAsyncFunc(inputValue, type), // 确保异步请求函数接收type参数
  {
    enabled: !!inputValue && inputValue.length > 2,
    staleTime: 5 * 60 * 1000, // 可根据业务需求调整缓存有效期
  }
);
  1. 确保传递给CacheAutocompleteField的queryAsyncFunc能接收type参数,在API请求中携带Type信息,让react-query基于完整查询键缓存对应结果。

问题2:切换Type时Autocomplete输入值未完全重置

Material UI的Autocomplete组件中,inputValue(输入框临时文本)和value(选中值)是独立状态,仅通过Formik重置字段值无法清空输入框的未匹配文本。需手动绑定并管理输入框状态,在Type变化时同步重置。

修复方案:

  1. 在CacheAutocompleteField中添加输入框状态管理,并监听Type变化触发重置:
const CacheAutocompleteField = ({
  field,
  form,
  cacheKey,
  queryAsyncFunc,
  type, // 接收当前Type值
  ...props
}) => {
  const [inputValue, setInputValue] = useState(field.value || "");

  // Type切换时,重置输入框文本和Formik字段值
  useEffect(() => {
    setInputValue("");
    form.setFieldValue(field.name, "");
  }, [type, form, field.name]);

  return (
    <Autocomplete
      {...props}
      inputValue={inputValue}
      onInputChange={(event, newInputValue) => {
        setInputValue(newInputValue);
      }}
      onChange={(event, newValue) => {
        form.setFieldValue(field.name, newValue);
      }}
      // 保留原有组件配置...
    />
  );
};
  1. 在父组件中给Country和City的CacheAutocompleteField传递当前Type值:
<CacheAutocompleteField
  name="country"
  cacheKey="countries"
  queryAsyncFunc={(input, type) => fetchCountries(input, type)}
  type={form.values.type}
  // 其他props配置...
/>
  1. 这样切换Type时,无论输入框是否有未匹配文本,都会自动清空输入框和对应Formik字段值。

内容的提问来源于stack exchange,提问作者Manspof

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:05:28