在 Formik Form 上更新 initialValues 道具不会更新输入值

新手上路,请多包涵

我像这样使用带有前向引用的 formik 形式

表单.js

 import React from "react";
import FormikWithRef from "./FormikWithRef";

const Form = ({
  formRef,
  children,
  initialValues,
  validationSchema,
  onSubmit
}) => {
  return (
    <FormikWithRef
      validateOnChange={true}
      validateOnBlur={true}
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={onSubmit}
      ref={formRef}
    >
      {(props) => <form onSubmit={props.handleSubmit}>{children}</form>}
    </FormikWithRef>
  );
};

export default Form;

FormikWithRef.js

 import React, { forwardRef, useImperativeHandle } from "react";
import { Formik } from "formik";

function FormikWithRef(props, ref) {
  let _formikProps = {};

  useImperativeHandle(ref, () => _formikProps);

  return (
    <Formik {...props}>
      {(formikProps) => {
        _formikProps = formikProps;
        if (typeof props.children === "function") {
          return props.children(formikProps);
        }
        return props.children;
      }}
    </Formik>
  );
}

export default forwardRef(FormikWithRef);

我有一些选项卡,更新 easy-peasy 存储状态 type ,当我选择第二个选项卡时,我想更新输入值(最初来自 value 的存储状态 --- ) with a Formik form, but updating state initialValues specific to that component that gets passed as initialValues prop to the Formik component.

TabsForm.js

 import React, { useState, useEffect, useRef } from "react";
import styled from "styled-components";
import { useStoreState } from "easy-peasy";
import Form from "./Form";
import MoneyBox from "./MoneyBox";

const Container = styled.div`
  width: 100%;
  background-color: #dfdfdf;
`;

const FieldWrapper = styled.div`
  padding: 20px 12px;
`;

const TabsForm = () => {
  const [initialValues, setInitialValues] = useState();

  const type = useStoreState((state) => state.type);
  const value = useStoreState((state) => state.value);

  const formRef = useRef(null);

  const onFormSubmit = async (values) => {
    console.log({ values });
  };

  useEffect(() => {
    if (value && type) {
      let filterVal = { ...value };
      /*  here is where I update the input value to be 3000,
      the initial values get updated and in the `Form.js` file,
      the console log from here also reflects this update,
      however, the input field does not update? */
      if (type === "Two") filterVal.input = 30000;
      setInitialValues(filterVal);
    }
  }, [value, type]);

  useEffect(() => {
    //   check initialValues has updated
    console.log({ initialValues });
  }, [initialValues]);

  return (
    <Container>
      {initialValues && type ? (
        <Form
          initialValues={initialValues}
          onSubmit={onFormSubmit}
          formRef={formRef}
        >
          <FieldWrapper>
            <MoneyBox name="input" currencySymbol={"£"} />
          </FieldWrapper>
        </Form>
      ) : null}
    </Container>
  );
};

export default TabsForm;

单击第二个选项卡时;

  • initialValues 状态 TabsForms.js 更新使得 value.input = 30000 ;
  • The initialValues prop in both Form.js and FormikWithRef.js also reflect that value.input = 3000
  • However, the input does not update, using the useField hook from forimk in the MoneyBox.js component, the field object does not have a value30000 ,而不是以前的字段值,这是为什么?

我创建了一个 CodeSandbox 来查看所有使用的组件,并创建了控制台日志以查看 Formik 确实收到了更新的值,但似乎没有应用它。

我已经坚持了几天,似乎找不到解决方案,我们将不胜感激。

原文由 mcclosa 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 959
2 个回答

If you want the value of the input to change when you change initialValues , you need to pass to the Formik component the prop enableReinitialize as true

因此,您需要在代码中更改的是 TabsForm.js 传递给您的 Form 组件 prop enableReinitialize

 <Form
  enableReinitialize
  initialValues={initialValues}
  onSubmit={onFormSubmit}
  formRef={formRef}
>
  <FieldWrapper>
    <MoneyBox name="input" currencySymbol={"£"} />
  </FieldWrapper>
</Form>

在你的 Form.js 中将该道具传递给 Formik 组件

const Form = ({
  formRef,
  children,
  initialValues,
  validationSchema,
  onSubmit,
  enableReinitialize
}) => {
  return (
    <FormikWithRef
      enableReinitialize={enableReinitialize}
      validateOnChange={true}
      validateOnBlur={true}
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={onSubmit}
      ref={formRef}
    >
      {(props) => <form onSubmit={props.handleSubmit}>{children}</form>}
    </FormikWithRef>
  );
};

我不太确定您的业务逻辑应该如何工作,但这是一个包含上述更改的 工作示例

原文由 Vencovsky 发布,翻译遵循 CC BY-SA 4.0 许可协议

解决方案 CodeSandbox

它叫做 initialValues ,那么为什么你希望它在你改变它时更新表单值呢? (但是你可以通过使用 enableReinitialize prop 来要求它这样做,正如@Vencovsky 在另一个答案中提到的那样。)

要将您想要的值( value.inputeasy-peasy 存储中)绑定到 formik 输入,您可以使用:

 const [field, meta, helpers] = useField(props);
useEffect(() => {
  helpers.setValue(value.input)
}, [value])

每当商店中的 value 发生变化时,它都会更新 formik 输入字段的值。

并且要更改存储状态的值,您可以使用设置选项卡的方式。 (使用 easy-peasy 存储。)

在 CodeSandbox 上运行

Tabs.js 的第 49 行,它会在单击选项卡时更新值。

Input.js 的第 19 行,它将输入值绑定到您的存储状态。

原文由 yaya 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题