前端嘛 Logo
前端嘛

下面代码中,点击 “+3” 按钮后,age 的值是什么?

import { useState } from 'react';

export default function Counter() {
  const [age, setAge] = useState(42);
  function increment() {
    setAge(age + 1); 
  }
  return (
    <>
      <h1>Your age: {age}</h1>
      <button onClick={() => {
        increment();
        increment();
        increment();
      }}>+3</button>
    </>
  );
}

参考答案

点击 +3 时,可能只更新为 43。

这是因为 setAge(age + 1) 即使多次调用,也不会立即更新组件状态,而是会进行合并,最终只触发一次重新渲染。

如果要实现调用三次就增加 3 ,可以将 increment 改为函数式更新:

function increment() {
    setAge(a => a + 1); // 函数式更新
}