React中的解构和状态的概念理解

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

Conceptual understanding for Destructuring and State in React

问题

以下代码运行正常。我只想了解,在从 e.target 解构出 name 和 value 后,为什么在设置数据时需要将 name 包裹在方括号中,为什么不能只使用变量 name 而不带方括号。

  function handleChange(e) {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  }
英文:

Below code works fine. I just want to understand that after destructuring of name and value from e.target, why name needs to be wrapped in square brackets while setting data. Why can't we use variable name without square brackets.

  function handleChange(e) {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  }

答案1

得分: 0

在您的情况下,您将拥有一个名为formData的对象,其键可能如下所示:

{
  firstName: 'John',
  lastName: 'Doe'
}

如果您按照您的示例更新对象,您将从输入事件中获取键,该键将是动态的,并由输入元素的name属性设置,例如"firstName"

因此,在这种情况下:

{
  ...formData,
  [name]: value,
}

实际结果将是:

{
  firstName: "Some new value", // 变量value的内容
  lastName: "Doe",
}

但是,如果您省略方括号,name变量将不会用作键,您将字面上使用字符串值"name"作为键,如下所示:

{
  firstName: "John",
  lastName: "Doe",
  name: "Some new value", // 变量value的内容
}

这不是您想要的。

英文:

In your case, you would have a formData object with keys that may look like this:

{
  firstName: 'John',
  lastName: 'Doe'
}  

If you would update the object like in your example, you would get the key from your input event which would be dynamic and set by the name prop of the input element, "firstName" for example.
So in the case

{
  ...formData,
  [name]: value,
}

the outcome would actually be

{
  firstName: "Some new value", // Content of the variable value
  lastName: "Doe",
}

But if you were to leave out the square brackets, the name variable wouldn't be used as key, you would literally use the string value "name" as the key, so:

{
  firstName: "John",
  lastName: "Doe",
  name: "Some new value", // Content of the variable value
}

which is not what you want.

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

发表评论

匿名网友

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

确定