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

使用Formik+MUI提交表单后无法重置多选复选框值

Formik + MUI 复选框提交后无法重置的解决方法

你的问题根源在于表单状态管理不一致:复选框的选中状态绑定了Formik的values,但更新时却修改了组件自己的loc状态,导致Formik无法跟踪复选框的真实状态,调用handleReset时只能重置Formik内部的values,却没同步清空loc,所以复选框看起来没重置。

修复方案:统一用Formik管理复选框状态

把复选框的状态完全交给Formik,去掉本地的useState(loc),让Formik负责所有表单状态的存储和更新,这样handleReset就能正常工作。

1. 修改主表单代码

const LeadForm = () => {
    // 去掉本地的loc状态,完全用Formik管理
    const handleSubmitForm = (values) => {
        // 从Formik的values中提取选中的地点
        const googleLocation = Object.keys(values.user_google_location)
            .filter(key => values.user_google_location[key])
            .join(',');

        const postData = {
            user_google_location: googleLocation,
        };
       
        Axios.post(`...url`, qs.stringify(postData))
            .then(response => {
                // ...some toast
            }).catch(err => console.log(err));
    };

    const locations = [
        { id: 1, typeValue: 'Delhi' },
        { id: 2, typeValue: 'Punjab' }
    ];

    return (
        <div className={Styles.FormDiv}>
            <Formik
                // 初始化选中状态为对象,每个地点对应一个布尔值
                initialValues={{
                    user_google_location: {}
                }}
                onSubmit={(values) => {
                    handleSubmitForm(values);
                }}
            >
                {({
                    values,
                    errors,
                    handleChange,                
                    handleSubmit,
                    handleReset
                }) => {
                    return <Form onSubmit={handleSubmit}>
                        {locations.map((e, index) => (
                            <div key={index}>
                                <CheckBoxSelectors
                                    id={e.id}
                                    // 传递Formik的values和handleChange
                                    values={values.user_google_location}
                                    handleChange={handleChange}
                                    label={e.typeValue}
                                />
                            </div> 
                        ))}
                        <button type="button" className={Styles.SubmitButton} 
                            onClick={() => {
                                handleSubmitForm(values);
                                // 调用Formik的handleReset,会重置到initialValues
                                handleReset();
                            }}
                        >
                            SUBMIT
                        </button>
                    </Form>;
                }}
            </Formik>
        </div>
    );
};

export default LeadForm;

2. 修改CheckboxSelectors组件

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';

const BlueCheckbox = withStyles({
    root: {
        '&$checked': {
            color: "#1c75c0",
        },
    },
    checked: {},
})((props) => <Checkbox color="default" {...props} />);

export default function CheckboxLabels(props) {
    const { label, values, handleChange } = props;
    // 用地点名称作为复选框的name属性
    const checkboxName = label;

    return (
        <div>
            <FormGroup>
                {/* 这里补充你原本的div内容 */}
                <FormControlLabel
                    label={label}
                    control={
                        <BlueCheckbox
                            // 从Formik的values中获取选中状态,默认false
                            checked={values[checkboxName] || false}
                            onChange={handleChange}
                            name={`user_google_location.${checkboxName}`}
                            color="primary"
                        />
                    }
                />
            </FormGroup>
        </div>
    );
}

关键说明

  • 用Formik的嵌套字段语法(user_google_location.${checkboxName})来更新对象类型的表单值,Formik会自动处理嵌套对象的更新。
  • 去掉本地loc状态后,所有复选框状态都存在Formik的values里,handleReset会把values重置为initialValues(空对象),复选框自然会变成未选中状态。
  • 如果之前混合使用本地状态和Formik状态,重置时不仅要调用handleReset,还要手动清空本地状态(比如setLoc({})),但更推荐统一用Formik管理表单状态,减少状态同步问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:37:45