You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中的pending state是什么?它与current state是否相同?

关于React中pending state的解释

什么是pending state?

pending state指的是当前更新队列中,上一个更新器函数计算后得到的中间状态值,它是React在批量处理状态更新队列时,传递给队列中下一个更新器函数的状态参数。

以你提供的代码为例:

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(42);

  function handleClick() {
    setCount(a => a + 1);
    setCount(a => a + 1);
    setCount(a => a + 1);
  }
  alert(count)
  return (
    <button onClick={handleClick}>
      You pressed me {count} times
    </button>
  );
}

点击按钮触发handleClick后,三个setCount的更新器函数会被加入更新队列:

  • 第一个更新器函数接收初始的稳定状态(42)作为pending state,计算出下一状态(43)
  • 第二个更新器函数接收前一个更新的结果(43)作为pending state,计算出下一状态(44)
  • 第三个更新器函数接收前一个更新的结果(44)作为pending state,计算出下一状态(45)

pending state和current state是否相同?

多数情况下不相同:

  • current state是组件当前渲染周期中使用的稳定状态值,是组件可以直接读取的状态(比如示例里初始的42,或者更新完成后的45)。
  • pending state是更新队列流转过程中的中间状态,仅在批量处理更新时作为更新器函数的参数传递,组件在当前渲染周期内无法直接读取该值。

只有当更新队列中仅存在一个更新器函数时,pending state才会等于当前的current state——因为没有前序更新,初始的current state就会作为这个更新器的pending state。

内容的提问来源于stack exchange,提问作者Alvah_Franey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:05:24