简体   繁体   中英

Why pre-increment does not work with setState

I have the following functional component

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

when i click on the Click me button, it does not work - notice that i am using pre-increment here ++count

but when i do the same thing with increment only

setCount(count++)

then it works.

Why it is not working with pre-increment?

Pre or Post increment, either way is the wrong way to increment a counter in React as both mutate state. State is also declared const , so it can't be updated anyway.

 const count = 0; ++count; // error console.log(count);

Use a functional state update.

setCount(c => c + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM