ReactJS:修改动态键值的数值

huangapple go评论59阅读模式
英文:

ReactJS: modify value of dynamic key value

问题

I have a react form with a list of "subform" as react component. I want to update the "global" form value from those child component.

One of my child component looks like that:

function ForecastForADay(props: any) {
  const { formValue, setFormValue } = useContext(FormContext)
  return (
    <>
      ...
      <input
        type="number"
        placeholder="0"
        className="form-control w-10"
        onChange={(x) =>
          setFormValue((oldVal: Forecasts) => {
            var nVal = oldVal;
            (nVal[props.objField as keyof Forecasts] as SingleForecast).temperatureMin = parseInt(x.target.value);
            return nVal;
          })
        }
      ></input>
      ...
    </>
  )
}

As you can see I use a context for the whole form value (cause there's multiple layers of component). My issue is that in the onChange function, it modifies all the fields of the nVal object instead of only modifying props.objField.

props.objField has the correct value which corresponds to a field's name.

Do you have any idea why this behavior occurs?

英文:

I have a react form with a list of "subform" as react component. I want to update the "global" form value from those child component.

One of my child component looks like that :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function ForecastForADay(props: any) {
  const { formValue, setFormValue } = useContext(FormContext)
  return (
    &lt;&gt;
      ...
       &lt;input
          type=&quot;number&quot;
          placeholder=&quot;0&quot;
          className=&quot;form-control w-10&quot;
          onChange={(x) =&gt;
            setFormValue((oldVal: Forecasts) =&gt; {
              var nVal = oldVal
              ;(nVal[props.objField as keyof Forecasts] as SingleForecast).temperatureMin = parseInt(x.target.value)
              return nVal
            })
          }
        &gt;&lt;/input&gt;
      ...
    &lt;/&gt;
  )
}

<!-- end snippet -->

As you can see I use a context for the whole form value (cause there's multiple layers of component). My issue is that in the onChange function, it modify all the fields of the nVal object instead of only modifying porps.objField.

props.objField as the correct value which corespond to a field's name.

Do you have any idea why this behaviour occurs?

答案1

得分: 1

你遇到的问题与JavaScript中的对象可变性有关。当你写var nVal = oldVal时,实际上是创建了一个对存储在oldVal中的同一对象的引用。因此,对nVal所做的任何更改也会影响oldVal。换句话说,oldValnVal都指向内存中的同一对象。

要避免这个问题,你应该在修改对象之前创建一个对象的副本。一种方法是使用扩展运算符(...)创建对象的浅拷贝。

setFormValue改为:

setFormValue((oldVal: Forecasts) => {
  const nVal = { ...oldVal }; // 创建对象的浅拷贝
  nVal[props.objField as keyof Forecasts] = {
    ...nVal[props.objField as keyof Forecasts], // 创建嵌套对象的浅拷贝
    temperatureMin: parseInt(x.target.value)
  };
  return nVal;
});
英文:

The issue you are experiencing is related to object mutability in JavaScript. When you write var nVal = oldVal, you are creating a reference to the same object that is stored in oldVal. Therefore, any changes made to nVal will also affect oldVal. In other words, both oldVal and nVal are pointing to the same object in memory.

To avoid this issue, you should create a copy of the object before modifying it. One way to achieve this is by using the spread operator (...) to create a shallow copy of the object.

Change setFormValue as:

setFormValue((oldVal: Forecasts) =&gt; {
  const nVal = { ...oldVal }; // Create a shallow copy of the object
  nVal[props.objField as keyof Forecasts] = {
    ...nVal[props.objField as keyof Forecasts], // Create a shallow copy of the nested object
    temperatureMin: parseInt(x.target.value)
  };
  return nVal;
});

huangapple
  • 本文由 发表于 2023年4月19日 17:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定