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]);
添加回答
举报