反应一种方法一个一个地改变两个状态结果不是我预期的

我刚刚开始学习 React。做一些简单的事情来练习。现在我正在尝试使用钩子。我创建了几个他们和模拟人生,他们不能同时改变渲染 我有一张商品表,想点击检查所有并输出所有商品的总价,或者如果它被检查为零。但是,当我单击它时,它会更改复选框的值但不会更改总价,而另一次它会更改总价但不会更改复选框...


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);

    }


我怎么能改变它来完成这项工作?我知道另一个人会使它完全不同,但这个案例非常有趣,这就是为什么我决定在这里问这个问题......


小怪兽爱吃肉
浏览 86回答 1
1回答

DIEA

问题setState是它是异步的,这意味着您的数据不会立即更新。为此useEffect,react has 可以在某些依赖项发生变化时运行一些逻辑。在这种情况下,您的依赖项是checkedGoods. 要在更改changeTotal时运行,您可以执行以下操作:changedGoodsconst ProductsListDemo = () => {&nbsp; &nbsp; const [total, setTotal] = useState(1720);&nbsp; &nbsp; const [checkedGoods, setCheckedGoods] = useState([&nbsp; &nbsp; &nbsp; &nbsp; true,&nbsp; &nbsp; &nbsp; &nbsp; true,&nbsp; &nbsp; &nbsp; &nbsp; true,&nbsp; &nbsp; &nbsp; &nbsp; true,&nbsp; &nbsp; ]);&nbsp; &nbsp; function checkAll(e) {&nbsp; &nbsp; &nbsp; &nbsp; let isChecked = (total == 0)? true: false;&nbsp; &nbsp; &nbsp; &nbsp; e.target.value = isChecked;&nbsp; &nbsp; &nbsp; &nbsp; const arr = [];&nbsp; &nbsp; &nbsp; &nbsp; for(let i = 0; i < checkedGoods.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr.push(isChecked);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; setCheckedGoods(arr);&nbsp; &nbsp; }&nbsp; &nbsp; function changeTotal(){&nbsp; &nbsp; &nbsp; &nbsp; let sum = 0;&nbsp; &nbsp; &nbsp; &nbsp; for(let i = 0; i < goods.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let total = goods[i].price * goods[i].amount;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum += (checkedGoods[i])? total: 0;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; setTotal(sum);&nbsp; &nbsp; }&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; changeTotal();&nbsp; &nbsp; }, [checkedGoods]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript