我的 React 组件中有这种状态-->
const [employeeState, setEmployee] = useState({
"empName": null,
"Age": null,
"depts": [], //depts is an array of objects
"groups": [] //group is an array of objects
});
我对部门和组有一个单独的状态,如下所示 -->
const depts = {
"name": "some name",
"code": "s123",
}
const [deptState, setDeptState] = useState([
{ ...depts},
]);
对于团体来说也是如此......
现在,当我尝试在某些 btn 单击上设置员工状态时,如下所示,它不会更新并保留 depts
和 groups
属性,因为它是空的 -->
const deptsLst = [...deptState];
const groupsLst = [...groupstate];
console.log(depsLst); // this will print the results as expected
console.log(groupsLst); // this will print the results as expected
setEmployee({
...employeeState,
['depts']: deptsLst ,
['groups']: groupsLst ,
})
console.log(employeeState);// this will show depts and groups as empty only
我对这个传播变量复制概念很陌生。我在这里做错了什么?
最佳答案
您说“我对这种传播变量复制概念很陌生”...您不仅对传播操作不熟悉,而且您的代码表明您对它没有基本的了解,我认为。您在计算属性名称之上的扩展运算符之上使用扩展运算符,这一切都是没有原因的。
您还使用 React 状态来管理员工对象,然后使用 React 状态来管理员工对象上的数组属性。如果您已经对员工对象执行状态管理,为什么还要维护各个属性的状态?
好的,对您的代码进行一些分割:
const depts = {
"name": "some name",
"code": "s123",
}
const [deptState, setDeptState] = useState([
{ ...depts},
]);
上面你无缘无故地克隆了一个对象。
使用 React 状态管理,您只需要克隆对象即可触发渲染事件。克隆在内存中创建一个具有新引用的新对象,将对对象引用更改做出“ react ”并触发状态更改事件。 React 无法监视复杂对象的每个属性,尤其是数组元素以查看值是否已更改。
下面的代码就足够了,您正在初始化状态,不需要克隆:
const [deptState, setDeptState] = useState([{
"name": "some name",
"code": "s123",
}]);
接下来是这段代码:
setEmployee({
...employeeState,
['depts']: deptsLst ,
['groups']: groupsLst ,
})
此处,您尝试使用扩展运算符来克隆“employeeState”对象并更新 depts
属性键和 groups
属性键的新值。您无缘无故地使用“计算属性名称”作为属性键。
这就足够了:
setEmployee({
...employeeState,
depts: deptsLst ,
groups: groupsLst
})
您还创建了不必要的状态:
const [deptState, setDeptState] = //..rest of code omitted
这里你没有意识到 React 状态变化是异步发生的:
setEmployee({
...employeeState,
['depts']: deptsLst ,
['groups']: groupsLst ,
})
console.log(employeeState);
上面的代码实际上改变了employeeState,只是不是你的console.log(employeeState)
的时间;
好的,首先我有 created a CodePen让您了解状态如何变化。
当您想要更改此员工对象的状态时,您只需更改对象属性值或添加新的属性值,然后克隆员工对象以更改其引用,然后使用克隆调用 setState,请考虑此对象状态:
const [employee, setEmployee] = React.useState({
"empName": 'Jane Doe',
"Age": 33,
"depts": [
{
"name": "some name",
"code": "s123",
}
]
});
这里我给员工添加了一个部门,注意我只是克隆了员工对象来触发React来检测整体对象引用的变化,React并不知道我改变了属性depts
数组,而是新的state 确实有我在部门数组上推送的新值:
function exampleUpdatingEmployee() {
employee.depts.push({
"name": "some new dept",
"code": "876",
});
setEmployee({ ...employee });
}
关于javascript - useState 更新状态子数组对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774574/