为什么预增量不适用于 setState

Why pre-increment does not work with setState

我有以下功能组件

const App = () => {
  const [count, setCount] = useState(0);
  const test = () => {
    setCount(++count);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={test}>Click me</button>
    </div>
  );
};

当我点击 Click me 按钮时,它不起作用 - 请注意我在这里使用的是预增量 ++count

但是当我用 increment only

做同样的事情时

setCount(count++)

然后就可以了。

为什么它不能使用预增量?

Pre 或 Post 递增,无论哪种方式都是在 React 中递增计数器的错误方式,因为两者都是变异状态。状态也已声明 const,因此无论如何都无法更新。

const count = 0;

++count; // error

console.log(count);

使用功能状态更新。

setCount(c => c + 1);