1 回答

TA貢獻1820條經驗 獲得超2個贊
問題setState是它是異步的,這意味著您的數據不會立即更新。為此useEffect,react has 可以在某些依賴項發生變化時運行一些邏輯。在這種情況下,您的依賴項是checkedGoods. 要在更改changeTotal時運行,您可以執行以下操作:changedGoods
const ProductsListDemo = () => {
const [total, setTotal] = useState(1720);
const [checkedGoods, setCheckedGoods] = useState([
true,
true,
true,
true,
]);
function checkAll(e) {
let isChecked = (total == 0)? true: false;
e.target.value = isChecked;
const arr = [];
for(let i = 0; i < checkedGoods.length; i++) {
arr.push(isChecked);
}
setCheckedGoods(arr);
}
function changeTotal(){
let sum = 0;
for(let i = 0; i < goods.length; i++) {
let total = goods[i].price * goods[i].amount;
sum += (checkedGoods[i])? total: 0;
}
setTotal(sum);
}
useEffect(() => {
changeTotal();
}, [checkedGoods]);
添加回答
舉報