Объединение React Final Form Array и Final Form Calculate

Мне очень трудно получить доступ к объектам в массиве полей для рассчитанной цены поля * количество = всего. Пробовали кучу регулярных выражений для украшенного поля, включая field: /invoiceItems\[\d+\]/ , для доступа и решение из этого PR (https://github.com/final-form/final-form-calculate/pull/21/commit/dab00f8125079fed402712a4b0ed71663be0ba14)

В PR я не могу получить доступ к индексу. Как лучше всего выполнить расчет с помощью вычислений окончательной формы и массивов? Я пробовал это и в Formik, но столкнулся с той же проблемой.

Код

Форма:

          onSubmit={onSubmit}
          decorators={[calculator]}
          mutators={{
            ...arrayMutators,
          }}
          initialValues={{
            companyName: "",
            companyAddress: "",
            companyCity: "",
            companyState: "",
            companyZip: "",
            invoiceNumber: shortid.generate(),
            invoicePaymentStatus: "",
            invoiceStatus: "",
            invoiceItems: [

            ],
            invoiceDate: new Date(),
            invoiceDueDate: new Date(
              new Date().getTime() + 7 * 24 * 60 * 60 * 1000
            ),
            clientFname: "",
            clientLname: "",
            billingAddress: "",
            billingCity: "",
            billingState: "",
            billingZip: "",
            propertyAddress: "",
            propertyCity: "",
            propertyState: "",
            propertyZip: "",
            invoiceTotal: "",
            tax: "",
          }}
          render={({
            handleSubmit,
            reset,
            submitting,
            pristine,
            values,
            form: {
              mutators: { push, pop },
            },
          }) => (
            <form onSubmit={handleSubmit} noValidate>

Массив полей:

                            type="button"
                            onClick={() => push("invoiceItems", undefined)}
                          >
                            Add Line Item
                          </button>
                          <FieldArray name="invoiceItems">
                            {({ fields }) =>
                              fields.map((item, index) => (
                                <div key={item}>
                                  <Field
                                    name={`${item}.description`}
                                    component={TextField}
                                    placeholder="Description"
                                  />
                                  <Field
                                    name={`${item}.price`}
                                    component={TextField}
                                    placeholder="Price"
                                  />
                                  <Field
                                    name={`${item}.quantity`}
                                    component={TextField}
                                    placeholder="Quantity"
                                  />
                                  <Field
                                    name={`${item}.total`}
                                    component={TextField}
                                    placeholder="Total"
                                  />
                                  <span
                                    onClick={() => fields.remove(index)}
                                    style={{ cursor: "pointer" }}
                                  >
                                    ❌
                                  </span>
                                </div>
                              ))
                            }
                          </FieldArray> 

Вот некоторые из декораторов, которые я пробовал. (Это катастрофа с таким количеством разных попыток и игнорированием математики, поскольку мы просто пытались заставить ее работать)


    { 
      field: /invoiceItems\[\d+\]/ ,
      updates: {(name, index, value) => {
        [`invoiceItems[${index}].total`]: (_ignored, values) =>  2 
        //invoiceItems.total: (price, allValues) => price * 2
      }
    }
  )

person dgresh24    schedule 16.04.2020    source источник


Ответы (1)


В конечном итоге исправил это на основе этого: Как объединить ли `final-form-calculate` с` final-form-array`

Вот готовый код:

const calculator = createDecorator(
  {
    field: /invoiceItems\[\d+\]\.price/,
    updates: (value, name, allValues) => {
      const totalField = name.replace(".price", ".total");
      const quantityField = name.replace(".price", ".quantity");
      return {
        [totalField]: parseInt(value) * parseInt(getIn(allValues, quantityField)),
      };
    },
  },
  {
    field: /invoiceItems\[\d+\]\.quantity/,
    updates: (value, name, allValues) => {
      const totalField = name.replace(".quantity", ".total");
      const priceField = name.replace(".quantity", ".price");
      return {
        [totalField]: parseInt(value) * parseInt(getIn(allValues, priceField)),
      };
    },
  }
);
person dgresh24    schedule 17.04.2020