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

Javascript 反应一种方法一个一个改变两种状态结果不是我预期的,javascript,reactjs,Javascript,Reactjs,我刚刚开始学习如何反应。做一些简单的事情来练习。现在我试着用钩子。 我创建了两个它们和模拟人生,它们不能同时更改渲染。我有一个商品表,希望单击“全部检查”,并输出所有商品的总价,或者如果它被检查为零。但是当我点击它时,它会改变复选框的值,但不会改变总价。另一次,它会改变总价,但不会改变复选框 const ProductsListDemo = () => { const [total, setTotal] = useState(1720); const [checkedG

我刚刚开始学习如何反应。做一些简单的事情来练习。现在我试着用钩子。 我创建了两个它们和模拟人生,它们不能同时更改渲染。我有一个商品表,希望单击“全部检查”,并输出所有商品的总价,或者如果它被检查为零。但是当我点击它时,它会改变复选框的值,但不会改变总价。另一次,它会改变总价,但不会改变复选框

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

constproductsListDemo=()=>{
const[total,setTotal]=useState(1720);
常量[checkedGoods,setCheckedGoods]=useState([
是的,
是的,
是的,
是的,
]);
功能检查全部(e){
让isChecked=(total==0)?true:false;
e、 target.value=已检查;
常数arr=[];
for(设i=0;i

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

关于
setState
的事情是它是异步的,这意味着你的数据不会立即更新。因为这个react具有
useffect
,w它可以在某些依赖项发生更改时运行某些逻辑。在这种情况下,您的依赖项是
checkedGoods
。要在
changedGoods
发生更改时运行
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]);
constproductsListDemo=()=>{
const[total,setTotal]=useState(1720);
常量[checkedGoods,setCheckedGoods]=useState([
是的,
是的,
是的,
是的,
]);
功能检查全部(e){
让isChecked=(total==0)?true:false;
e、 target.value=已检查;
常数arr=[];
for(设i=0;i{
changeTotal();
},[checkedGoods]);

看起来您的逻辑有一些缺陷。为什么不发布整个React组件,而不仅仅是组件功能。因为这个网站写道,我试图发布很多代码((当您使用表单和React,以及使用功能组件和挂钩时,我建议您查看“React Hook forms”库并使用它处理表单。谢谢,我将查看它是的,这很有帮助,非常感谢))