简体   繁体   English

如何使用 useEffect 从 formik 中获取价值?

[英]How to get value inside formik out using useEffect?

my full code https://codesandbox.io/s/testproducr02-bg7exz?file=/index.tsx我的完整代码https://codesandbox.io/s/testproducr02-bg7exz?file=/index.tsx

 const [sum, setSum] = useState(0);
 const [qty, setQty] = useState(0);
useEffect(() => {
    const sum = values.product.reduce((acc, item) => acc + item.qty * 1, 0); //error values is not defined
    setSum(sum);
  });

useEffec t is outside formik , but I don't know how to get the value out useEffecformik之外,但我不知道如何获取value

this is inside my formik这是在我的formik里面

  <Formik
        initialValues={initialValues}
        onSubmit={async (values) => {
          await new Promise((r) => setTimeout(r, 500));
          //alert(JSON.stringify(values, null, 2));

          // const sum = values.product.reduce(
          //   (acc, item) => acc + item.qty * 1,
          //   0
          // );
          // setSum(sum);
        }}
      >
        {({ values }) => (
          <Form>
            <FieldArray name="product">
              {({ insert, remove, push }) => (
                <div>
                  {values.product.length > 0 &&
                    values.product.map((friend, index) => (
                      <div className="row" key={index}>
                        <div className="col">
                          <label htmlFor={`product.${index}.productname`}>
                            Productname
                          </label>
                          <Field
                            name={`product.${index}.productname`}
                            placeholder="productname"
                            type="text"
                          />
                        </div>
                        <div className="col">
                          <label htmlFor={`product.${index}.qty`}>Qty</label>
                          <Field
                            name={`product.${index}.qty`}
                            placeholder="qty"
                            type="number"
                          />
                        </div>
                        <div className="col">
                          <button
                            type="button"
                            className="secondary"
                            onClick={() => remove(index)}
                            style={{ marginTop: "10px" }}
                          >
                            Delete
                          </button>
                        </div>
                      </div>
                    ))}
                  <label>Sum</label>
                  <Field
                    name={`sum`}
                    placeholder="sum"
                    type="text"
                    value={sum}
                    disabled
                  />
                  <br />
                  <button
                    type="button"
                    className="secondary"
                    onClick={() =>
                      push({ productname: "", qty: 0, price: 0, amount: 0 })
                    }
                  >
                    Add Product
                  </button>
                </div>
              )}
            </FieldArray>
            <p>Qty : {qty}</p>
            <p>sum : {sum}</p>

            <button type="submit">Summit</button>
          </Form>
        )}
      </Formik>

i want to calculate it without pressing onSubmit我想在不按onSubmit的情况下calculate

You can use Formik 's innerRef prop to attach a ref to the Formik component.您可以使用FormikinnerRef将 ref 附加到 Formik 组件。

    // ...
    const formikRef = useRef(null);
    // ...
    return (
        <Formik
            initialValues={initialValues}
            innerRef={formikRef}
            // ...
        >
            ...
        </Formik>
    );

And then in some useEffect然后在一些useEffect

if (formikRef.current) {
    const productData = formikRef.current.values.product
    // do something

}

I believe there are other methods too, such as "Formik Context"我相信还有其他方法,例如“Formik Context”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM