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

Formik表单无法设置后端返回的初始值,报TS2322类型错误

报错根因

该TS2322报错的触发原因是initialValues状态初始化时未赋值,首次渲染时为undefined,不符合Formik要求initialValues必须为FormikValues类型对象的类型约束。

解决步骤

1. 给initialValues设置匹配表单结构的默认值

你的表单用到了count/countone/counttwo/countthree/helptext5个字段,初始化状态时直接给定默认结构即可:

// 把原来的 const [initialValues, setInitialValues] = useState(); 替换为
const [initialValues, setInitialValues] = useState({
  count: 0,
  countone: 0,
  counttwo: 0,
  countthree: 0,
  helptext: ''
});

注意要保证后端接口返回的response.data字段结构和上述默认结构完全一致,避免后续赋值后出现字段缺失的问题。

2. 可选:新增初始数据加载判断

如果不想用默认值渲染表单,可以新增初始数据加载状态,接口请求完成前展示加载动画:

// 新增加载状态
const [fetchingInitial, setFetchingInitial] = useState(true);

// 修改useEffect逻辑
useEffect(() => {
  getInitialValues().then((res:any) => {
    if(res) setInitialValues(res);
    setFetchingInitial(false);
  });
}, []);

// 渲染时新增判断逻辑
return (
  <React.Fragment>
    {fetchingInitial ? 
      <CircularProgress style={{ margin: '2em' }} /> :
      <Formik
        enableReinitialize
        initialValues={initialValues}
        validationSchema={contactSchema}
        // 其余Formik配置保持不变
      >
        {/* 原有表单内容保持不变 */}
      </Formik>
    }
  </React.Fragment>
)

3. 优化建议(可选)

你当前单独维护的count/countone等本地状态可以直接用Formik内置的表单状态替代,避免两边状态不同步:点击点赞图标时直接调用Formik提供的setFieldValue方法修改表单对应字段即可,无需单独声明useState存储计数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:42:00