[英]Change a value in a nested object using useState in reactJs
我正在尝试使用 useState 更改嵌套在嵌套在对象内的数组中的对象属性的值。
状态设置如下:
const [groupState, setGroupState] = useState({
groupId: uuidv4(),
content: [{ rowId: uuidv4(), field: '', from: '', to: '' }],
});
我正在尝试更改“字段”属性的值。 如果我在 required 属性中添加具有所需值的整个“虚拟”对象,则它可以工作:
setGroupState({
...groupState,
content: groupState.content.map((item) => {
if (item.rowId === rowId) {
return (item = { rowId: uuidv4(), field: value, from: '', to: '' });
}
}),
});
但是,我只需要更新特定的属性值,而不是整个对象。 我最近的努力如下:
setGroupState({
...groupState,
content: groupState.content.map((item) => {
if (item.rowId === rowId) {
return (item.field = value);
}
}),
});
它返回错误:“无法在字符串 'user' 上创建属性 'field'” - 我做错了,但我不知道是什么。
尝试销毁您的 item 对象:
setGroupState({
...groupState,
content: groupState.content.map((item) => ({
...item,
field: item.rowId === rowId ? value : item.field,
})),
});
// Without explicit return
setGroupState({
...groupState,
content: groupState.content.map((item) => {
return { ...item, field: item.rowId === rowId ? value : item.field };
}),
});
好的,明白了,谢谢丹尼斯·瓦什 - 只需要一点点改变:
setGroupState({
...groupState,
content: groupState.content.map((item) => ({
...item,
field: item.rowId === rowId ? value : item.field,
})),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.