React useState 落后一步

React useState is one step behind

所以我在这里阅读了很多关于该主题的其他帖子,但根据我看到的答案,我仍然无法解决我的问题。我正在创建两个计数器并将它们的状态用作数组中的值(只是为了玩弄 React,没有实际或逻辑上的用途)我想将计数器数组传递给另一个组件。但是,数组中的值并未显示更新后的状态(即在控制台日志中),而是始终落后一步。我知道这是因为它是异步的,我应该以某种方式使用 useEffect,但我根本不知道我应该如何做到这一点才能使其按预期工作。我是 React 的新手 - 任何帮助将不胜感激!

function Counter() {
    const [count1, setCount1State] = useState(0);
    const [count2, setCount2State] = useState(0);
    

    let counters = [
        { name: 1, count: count1State },
        { name: 2, count: count2State },
       
    ];

    useEffect(() => {
        //WHAT SHOULD I DO HERE TO HAVE COUNTERS HOLDING THE LATEST STATE VALUES?
    }, [count1, count2]);

    function increaseCounter(name: number) {
        switch (name) {
            case 1: {
                setCount1State(count1 + 1);
                break;
            }
            case 2: {
                setCount2State(count2 + 1);
                break;
            }
        }
    }

    function decreaseCounter(name: number) {
        switch (name) {
            case 1:        
                    setCount1State(count1 - 1);
                    break;
            }

            case 2:
                    setCount2State(count2 - 1);
                    break;
            }
        }
    }

你不需要useEffect。

function Counter() {
    const [count1, setCount1State] = useState(0);
    const [count2, setCount2State] = useState(0);

    function increaseCounter(name: number) {
        switch (name) {
            case 1: {
                setCount1State(count1 + 1);
                break;
            }
            case 2: {
                setCount2State(count2 + 1);
                break;
            }
        }
    }

    function decreaseCounter(name: number) {
        switch (name) {
            case 1:        
                    setCount1State(count1 - 1);
                    break;
            }

            case 2:
                    setCount2State(count2 - 1);
                    break;
            }
        }
    }
    return {
    <>
            <h3>Counter1: {count1}</h3>
            <h3>Counter2: {count2}</h3>
            <Button onClick={() => increaseCounter(1)}>IncreaseCounter1</Button>
            <Button onClick={() => increaseCounter(2)}>IncreaseCounter2</Button>
    </>};
    };

等等

如果您只是希望重新渲染表示状态的组件(或包含在 JSX 中的元素),则无需使用钩子。它会在状态更改后立即更新。你应该像这样发送值:

// if component is used:
return <Component state={state} changeState={setState} />
// in case of JSX element usage:
return <div>{state}</div>

UseEffect 用于一些额外的工作,如其他状态更新、DOM 更改、获取数据等。使用它时,请非常小心依赖项列表。这是你的例子:

useEffect(() => {
  // fetching data etc
}, [count1, count2]);

在这里,您将 count1 和 count2 状态设置为挂钩的依赖项。换句话说,当这些状态中的任何一个发生变化时,钩子就会触发。这意味着你不应该改变钩子内的任何状态,否则你会得到一个无限循环。