![](/img/trans.png)
[英]Adding a New Value to State is Overwriting Previous State in React Redux
[英]Adding a value to the state array results in replacement of previous value - React hooks
我試圖通過 onchange 將新值從復選框添加到 state 數組。 但是該值替換了以前的值。
const [checked, setCheck] = useState([]);
const changeCheck = (event,sku) =>{
event.preventDefault();
setCheck(prevChecked => [...prevChecked,sku]);
}
return(
<input type="checkbox" checked={checked.includes(props.details.sku)} onChange={(event) => changeCheck(event,props.details.sku)}/>
)
想要將 props.details.sku 值添加到選中的 state 數組中。 新值被添加到數組中,但舊值被替換也意味着 state 數組的長度仍然為 1。
為了更新復選框 state 您需要使用以前的 state 並決定是否需要添加或刪除復選框值
還使用 state 更新程序回調來更新 state
const [checked, setCheck] = useState([]);
const changeCheck = (event,sku) =>{
event.preventDefault();
setCheck(prevChecked => {
if(prevChecked.includes(sku)) {
// checkbox was checked previously so uncheck it
return prevChecked.filter(i => i !== sku);
} else {
// check the checkbox i.e add the id in array
return [...prevChecked, sku]
}
});
}
return(
<input type="checkbox" checked={checked.includes(props.details.sku)} onChange={(event) => changeCheck(event,props.details.sku)}/>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.