跳到主要内容

usePrevious

跟踪更新前的值

Usage

实时编辑器

function Demo() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <p>
        Now: {count}, before: {prevCount}
      </p>
    </div>
  );
};

结果
Loading...

API

usePrevious

Returns

T | undefined: 更新前的值

Arguments

参数名描述类型默认值
state状态值T (必填)-