我刚刚开始学习如何做出反应。做一些简单的事情来练习。现在我正在尝试使用钩子。我创建了几个它们和模拟人生,它们不能同时改变渲染,我有一个货物表,想要点击全部并输出所有商品的总价格,或者如果它被选中为零。但当我点击它时,它会改变复选框的值,但不会改变总价,下次它会改变总价,但不会改变复选框。
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);
changeTotal();
}
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);
}怎样才能改变它来让它工作呢?我知道另一个人会让它完全不同,但这个案例很有趣,这就是为什么我想在这里问它的原因。
发布于 2020-10-14 05:39:01
setState的特点是它是异步的,这意味着您的数据不会立即更新。为此react提供了useEffect,它可以在某些依赖关系发生变化时运行一些逻辑。在这种情况下,您的依赖项是checkedGoods。要在changedGoods发生更改时运行changeTotal,您可以执行以下操作:
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]);https://stackoverflow.com/questions/64342170
复制相似问题