[英]using setState to add a object in nested array
我正在使用 ireact 设置状态并尝试将数据发布到与数组嵌套的对象中。
这是我的默认状态:
const [data, setData] = useState({
working_hours: [
{
id: '',
description: '',
hours: '',
price: '',
total: '',
},
],
parts: [
{
id: '',
description: '',
unit: '',
quanity: '',
price: '',
total: '',
},
],
other: [
{
id: '',
description: '',
quanity: '',
price: '',
total: '',
},
],
});
您并不遥远,但是您需要复制外部对象和要推送到的数组。 使用回调表单也很重要,因为您正在根据现有状态更新状态,因此您要确保您拥有最新的状态:
const handleAdd = () => {
setData(data => {
const test = {
id: 3,
description: 'This is a description',
hours: 4.2,
price: 500,
total: 4421,
};
return {
...data,
working_hours: [...data.working_hours, test]
};
});
};
让我们看看您的代码是如何工作的。 你有一个对象,它具有三个属性
working_hours<\/code> 、
parts<\/code>和
others<\/code> (它们都是数组)。
现在当你写
setData({ ...data, working_hours: test });<\/code>
,幕后发生的事情是,首先将
data<\/code>的所有属性复制到一个新对象中,然后将属性
working_hours<\/code>替换为
test<\/code> 。
但是,您真正想要的是将
test<\/code>附加到
data.working_hours<\/code> 。
这就是你的做法
setData({...data, working_hours:[...data.working_hours, test])<\/code>
这里发生的事情是,首先,使用对象
data<\/code>的所有属性创建一个新对象。
然后创建一个新数组,其中包含
data.working_hours<\/code> (先前状态的
working_hours<\/code> )和
test<\/code>的所有元素。
这个数组被分配给新对象的
working_hours<\/code>属性,最后这个状态被分配给
new object<\/code> 。
这应该工作
const handleAdd = () => {
const test = {
id: 3,
description: 'This is a description',
hours: 4.2,
price: 500,
total: 4421,
};
const newData = {
...data,
working_hours: [
...(data?.working_hours ? data.working_hours : {}),
test
]
};
setData(newData);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.