简体   繁体   English

ReactJS 修改对象数组的特定属性

[英]ReactJS modify array of objects spesific property

i got array of objects that assigned in state and i want to modify a property with input field.我得到了在 state 中分配的对象数组,我想用输入字段修改属性。 I tried some below:我在下面尝试了一些:

 <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])}}
         />

and array is like:和数组就像:

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

These one only adds first letter that i wrote in keyboard.I need to achieve that proper working input field.这些只添加了我在键盘上写的第一个字母。我需要实现正确的工作输入字段。

You're directly modifying the object, which isn't allowed with React's state mechanism.您正在直接修改 object,这在 React 的 state 机制中是不允许的。 Instead, you need to copy the object, not just the array it's in:相反,您需要复制object,而不仅仅是它所在的数组:

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;
    }));
}}

A couple of side notes:一些旁注:

  • Notice I used currentTarget , not target .请注意,我使用currentTarget ,而不是target It's not important in this specific example because the element is an input , which by definition can't have children, so target and currentTarget will be the same thing.在这个特定示例中它并不重要,因为元素是input ,根据定义它不能有子元素,因此targetcurrentTarget将是同一件事。 But it can be important in many other situations, such as with button or select elements.但它在许多其他情况下可能很重要,例如使用buttonselect元素。
  • Since you're changing ingName based on user input, ingName shouldn't be the key of the element.由于您正在根据用户输入更改ingNameingName不应该是元素的key The user could make the ingName the same as another ingName .用户可以使ingName与另一个ingName相同。 Instead, give the object some unique identifier and use that.相反,给 object 一些唯一标识符并使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM