我能确定下一次 React 渲染时它会使用最新的状态值吗?

Can I be sure that the next time React renders it will use the most recent state value?

React 文档中有很多地方说 React 可以将一批状态更改放入队列并在以后一次性完成。

React Component Docs

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

React Hooks API Reference

Basic Hooks - useState

const [state, setState] = useState(initialState);

Returns a stateful value, and a function to update it.

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

问题 1

我的问题是:无论 React 决定在单个批次上执行多少个状态更新,我是否可以相信下一个渲染将使用最新状态以及自最后渲染?

问题 2

我可以依赖 React 决定排队的那些状态变化的顺序吗?我的意思是,如果我 setState({a:1}) 然后 setState({a:2}) 我能确定我状态的最终值是 2 吗?

问题 1:不,React 只能渲染(例如)更新队列的一半,然后是另一半。

问题二:是的。处理更新的顺序可能不像您调用 setState 的顺序那么简单,但最终,插入顺序决定了您状态的最新版本。

详细解释在react code.