[英]Pushing objects in an array only returns last object pushed in react
I Know this question to be duplicated, but none of the other answers worked for me... I am trying to push objects to my array using the onChnage method.我知道这个问题是重复的,但没有其他答案对我有用......我正在尝试使用 onChnage 方法将对象推送到我的数组。 But every time my array returns the last value, not the full value.
但每次我的数组返回最后一个值,而不是完整值。 I tried so many times to fix this issue.
我尝试了很多次来解决这个问题。 But I can't.
但我不能。
function addVariantSection(data) {
const handleChecked = (id) => (e) => {
const tempData1=[];
const { checkedID } = e.target;
const vID = e.currentTarget.id.split('-', 1);
tempData1.push({ productId:itemID, variantId:vID})
setChecked((values) => ({ ...values, [id]: checkedID, }));
setVariant([...tempData1]); // variant always give the last value.
};
return (
<Grid key={data._id} container spacing={10}>
<Grid item xs={12} style={{ justifyContent: 'space-between', display: 'flex' }}>
<div>{`${data.variant1}-${data.variant2}`}</div>
{/* eslint-disable-next-line no-useless-concat */}
<Checkbox id={`${data._id}-` + `checkData`} color="primary" checked={checked[data._id]} onChange={handleChecked(data._id)} />
</Grid>
</Grid>
);
}
You are overwriting setVariant
with the array - tempData1
.您正在使用数组 -
tempData1
setVariant
So you need to preserve the previous value of setVariant
to get the complete array you are expecting.因此,您需要保留
setVariant
的先前值才能获得您期望的完整数组。
So do this instead所以改为这样做
setVariant((prev) => ([...prev, ...tempData1]));
Your function will look like this:您的 function 将如下所示:
const handleChecked = (id) => (e) => {
const tempData1=[];
const { checkedID } = e.target;
const vID = e.currentTarget.id.split('-', 1);
tempData1.push({ productId:itemID, variantId:vID})
setChecked((values) => ({ ...values, [id]: checkedID, }));
setVariant((prev) => ([...prev, ...tempData1]));
};
You are simply setting the value of variant as a new array here, which is going to have tempData1
:您只需在此处将 variant 的值设置为一个新数组,该数组将具有
tempData1
:
setVariant([...tempData1]);
Firstly you need the previous value of variant, so the callback pattern for setState is going to be useful.首先,您需要变量的先前值,因此 setState 的回调模式将很有用。 It gives a reliable value for the previous state always .
它始终为以前的 state 提供可靠的值。 And using spread
...
, simply append the new object at the end.并使用 spread
...
,最后只需 append 新的 object。
const handleChecked = (id) => (e) => {
const { checkedID } = e.target;
const vID = e.currentTarget.id.split('-', 1);
setChecked((values) => ({ ...values, [id]: checkedID, }));
setVariant((variant) => { return [...variant,{ productId:itemID, variantId:vID}]}); // variant always give the last value.
};
The answers above should be ok, but if you don't want the format where you put a function inside a setState
what you can do is:上面的答案应该没问题,但是如果您不想要将 function 放入
setState
的格式,您可以做的是:
const [variant, setVariant] = useState([]);
.
.
.
setVariant([...variant, ...tempData1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.