[英]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:一些旁注:
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
,根据定义它不能有子元素,因此target
和currentTarget
将是同一件事。 But it can be important in many other situations, such as with button
or select
elements.button
或select
元素。ingName
based on user input, ingName
shouldn't be the key
of the element.ingName
, ingName
不应该是元素的key
。 The user could make the ingName
the same as another ingName
.ingName
与另一个ingName
相同。 Instead, give the object some unique identifier and use that.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.