【问题标题】:ReactJS modify array of objects spesific propertyReactJS 修改对象数组的特定属性
【发布时间】:2021-05-31 17:54:53
【问题描述】:

我得到了在状态中分配的对象数组,我想用输入字段修改属性。 我在下面尝试了一些:

 <input
         key={item.ingName}
           type="text"
           className="form-control"
           placeholder={item.ingName}
           name="ingName"
           value={item.ingName}
           onChange={(e) => {
             item.ingName = e.target.value
            setIngredients([...ingredients])}}
         />

和数组就像:

    ingredients : [{ingName: "meat", quantity: "1", unit: "kilogram"},
{ingName: "pickles", quantity: "100", unit: "grams"}]

这些只添加了我在键盘上写的第一个字母。我需要实现正确的工作输入字段。

【问题讨论】:

  • 值和名称是一样的吗??您对两者都使用ingName。这似乎……很奇怪。如果你要改变它,它不应该是key

标签: javascript arrays reactjs object


【解决方案1】:

您正在直接修改对象,这在 React 的状态机制中是不允许的。相反,您需要复制对象,而不仅仅是它所在的数组:

onChange={(e) => {
    setIngredients(ingredients.map(ingredient => {
        if (ingredient === item) {
            // This is the one we want to update, make and update a copy
            return {...ingredient, ingName: e.currentTarget.value};
        }
        // Not the one we want to update, we can keep using it
        return ingredient;
    }));
}}

一些旁注:

  • 请注意,我使用的是currentTarget,而不是target。在这个具体的例子中它并不重要,因为元素是一个input,根据定义它不能有子元素,所以targetcurrentTarget 将是同一个东西。但它在许多其他情况下可能很重要,例如buttonselect 元素。
  • 由于您要根据用户输入更改ingName,因此ingName 不应该是元素的key。用户可以使ingName 与另一个ingName 相同。相反,给对象一些唯一的标识符并使​​用它。

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 2013-05-17
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多