Formik复选框不会重新呈现

时间:2019-10-24 13:39:23

标签: reactjs formik

我正在使用Formik库,并且有一个带有一个复选框的简单表单,我想在更改时提交该表单:

export function rate(paymentsPerYear, paymentAmount, presentValue, futureValue, dueEndOrBeginning, interest)
{
  //If interest, futureValue, dueEndorBeginning was not set, set now
  if (interest == null)
    interest = 0.01;

  if (futureValue == null)
    futureValue = 0;

  if (dueEndOrBeginning == null)
    dueEndOrBeginning = 0;

  var FINANCIAL_MAX_ITERATIONS = 1280;//Bet accuracy with 128
  var FINANCIAL_PRECISION = 0.0000001;//1.0e-8

  var y, y0, y1, x0, x1 = 0, f = 0, i = 0;
  var rate = interest;
  if (Math.abs(rate) < FINANCIAL_PRECISION)
  {
    y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
  }
  else
  {
    f = Math.exp(paymentsPerYear * Math.log(1 + rate));
    y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
  }
  y0 = presentValue + paymentAmount * paymentsPerYear + futureValue;
  y1 = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;

  // find root by Newton secant method
  i = x0 = 0.0;
  x1 = rate;
  while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION)
  && (i < FINANCIAL_MAX_ITERATIONS))
  {
    rate = (y1 * x0 - y0 * x1) / (y1 - y0);
    x0 = x1;
    x1 = rate;

    if (Math.abs(rate) < FINANCIAL_PRECISION)
    {
      y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
    }
    else
    {
      f = Math.exp(paymentsPerYear * Math.log(1 + rate));
      y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
    }

    y0 = y1;
    y1 = y;
    ++i;
  }
  return rate;
}

由于某种原因,看起来好像每次单击后都不会重新渲染输入,而只是在第二次单击后才重新渲染。结果复选框未更新-您必须单击两次以进行更改(onChange事件仅在第二次触发)

我可以通过添加script.sh来强制重新渲染,但这是一个hack。

这是沙箱:https://codesandbox.io/s/formik-checkbox-issue-ew65e

1 个答案:

答案 0 :(得分:1)

您的问题是您试图在每次更改时提交表单。

理想情况下,您应该消除这种行为(也许使用lodash吗?):

import _ from 'lodash'

<form onChange={_.debounce(handleSubmit, 300)}>

或者,如果您不使用lodash,则可以通过将其包装在setTimeout中来使对handleSubmit的调用异步:

<form onChange={() => setTimeout(handleSubmit, 0)}>