为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

小怪兽爱吃肉 2023-05-11 16:58:27
我刚刚开始学习 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);    }我怎么能改变它来完成这项工作?我知道另一个人会使它完全不同,但这个案例非常有趣,这就是为什么我决定在这里问这个问题......
查看完整描述

1 回答

?
DIEA

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


查看完整回答
反对 回复 2023-05-11
  • 1 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信