setState() 完成后如何调用函数

sho*_*sho 3 reactjs react-hooks

我创建了一个这样的函数。

export function Counter() {

    const [count, setCount] = useState(0);

    const countUp = () => {
        setCount(count + 1);
    }

    const countUpAndShow = () => {
        setCount(count + 1);
        alert(count);
    }

    // I won't call after countUp function, call only countUpAndShow function.
    useEffect(() => {
        alert(count);
    },[count])

    return <div>
        <button onClick={countUp}>count up!</button>
        <button onClick={countUpAndShow}>show count!</button>
    </div>
}

Run Code Online (Sandbox Code Playgroud)

我想alert(count)稍后再打电话setCount()。但alert(count)无法正确显示计数。

然后,我useEffect像上面一样使用。alert()但我只想调用countUpAndShow函数。怎么解决呢?

Dre*_*ese 5

有多种方法可以解决这个问题。我建议使用 React ref 来切换show“状态”,以便它可以存在于 React 组件生命周期和 React hook 依赖项之外。我还建议在增加计数器状态值时使用功能更新,因为这将正确地从任何先前的状态与回调排队的状态进行更新。换句话说,它避免了过时的状态封闭。

function Counter() {
  const show = useRef(false);
  const [count, setCount] = useState(0);

  const countUp = () => {
    setCount((count) => count + 1);
  };

  const countUpAndShow = () => {
    setCount((count) => count + 1);
    show.current = true;
  };

  useEffect(() => {
    if (show.current) {
      alert(count);
      show.current = false;
    }
  }, [count]);

  return (
    <div>
      <button onClick={countUp}>count up!</button>
      <button onClick={countUpAndShow}>show count!</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑设置状态完成后如何调用函数