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

如何解决Formik状态选择器选中后跳回默认选项的异常问题?

问题分析与修复方案

核心问题

  1. 下拉框未绑定Formik表单的实时值,导致DOM显示与内部状态不同步
  2. 使用全局变量维护选中值,违反React状态管理逻辑,组件重渲染时会丢失状态
  3. 选项显示条件依赖初始值initialValues而非当前表单值,选择后对应选项可能被隐藏,下拉框自动回退到默认选项

修复后的代码

const selectField = ({ form, field, ...props }) => {
  const currentStatus = field.value?.toString();

  return (
    <select
      className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-teal-500 focus:border-teal-500 block w-full p-2.5"
      name={field.name}
      data-accordion={props['data-accordion']}
      onChange={(e: React.FormEvent<HTMLSelectElement>) => {
        const selectedValue = e.currentTarget.value;
        form.setFieldValue(field.name, selectedValue);
        setVisibleReasonMessage(selectedValue === "3" || selectedValue === "4");
      }}
      value={field.value || ""}
    >
      <option value="">Seleccionar</option>
      {currentStatus !== "2" && <option value="2">Aprobar</option>}
      {currentStatus !== "2" && currentStatus !== "4" && currentStatus !== "3" && (
        <option value="3">Rechazar</option>
      )}
      {currentStatus !== "4" && <option value="4">Retirar</option>}
    </select>
  );
};

// 渲染部分
<div className="relative z-0 w-full group my-2">
  <Field component={selectField} name="status" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-teal-500 focus:border-teal-500 block w-full p-2.5" />
  <ErrorMessage name="status" component="span" className="mt-2 text-xs text-red-600" />
  <p className="mt-2 text-xs text-red-600 hidden">Completa este campo</p>
</div>

关键修改说明

  • 移除全局变量selectValue,直接在onChange中获取当前选中值
  • 给<select>添加value={field.value || ""},让下拉框显示与Formik表单状态完全同步
  • 将选项显示条件的判断依据从initialValues.status改为field.value(当前表单实时状态),避免选择后对应选项被隐藏
  • 简化条件判断写法,保持逻辑清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:43