亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

反應一種方法一個一個地改變兩個狀態結果不是我預期的

反應一種方法一個一個地改變兩個狀態結果不是我預期的

小怪獸愛吃肉 2023-05-11 16:58:27
我剛剛開始學習 React。做一些簡單的事情來練習?,F在我正在嘗試使用鉤子。我創建了幾個他們和模擬人生,他們不能同時改變渲染 我有一張商品表,想點擊檢查所有并輸出所有商品的總價,或者如果它被檢查為零。但是,當我單擊它時,它會更改復選框的值但不會更改總價,而另一次它會更改總價但不會更改復選框...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 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號