如何在react js中更新对象值的setstate数组



如何更新setChoices对象值,下面是我的问题示例:我有一个包含值的对象的choices数组。在setstate(setChoices(上要更新对象值。

let [choices, setChoices] = useState({
Choices: [
{
OneChoiceWithValueSelected: {
OptionSelected: '15518',
Price: 0.9,
Quantity: 1,
},
ProductOptionId: 5712,
},
],
Note: 'test message',
ProductId: 6,
Quantity: 1,
StoreId: '6',
TableId: 0,
});
const demo = () => {
setChoices({
Choices: [
{
OneChoiceWithValueSelected: {
OptionSelected: '15518',
Price: 100,
Quantity: 12,
},
ProductOptionId: 5712,
},
],
Note: 'its a new message',
ProductId: 6,
Quantity: 10,
StoreId: '10',
TableId: 0,
});
alert(JSON.stringify(choices));
};
return (
<div>
<button onClick={demo}>test</button>
</div>
);

根据您的状态结构,您必须更新setChoices部分,如下所示

const demo = () => {
setChoices({
Choices[0].OneChoiceWithValueSelected.OptionSelected: '15518',
Choices[0].OneChoiceWithValueSelected.Price: 100,
Choices[0].OneChoiceWithValueSelected.Quantity: 12,
Choices[0].ProductOptionId: 5712,
Note: 'its a new message',
ProductId: 6,
Quantity: 10,
StoreId: '10',
TableId: 0
})
alert(JSON.stringify(choices))
}

您必须访问第0个数组元素才能更新其属性,因为OneChoiceWithValueSelected对象是Choices数组的第一个元素,然后使用对象表示法访问其他元素。

最新更新