React 是否保持状态更新的顺序? [英] Does React keep the order for state updates?

查看:49
本文介绍了React 是否保持状态更新的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 React 可能会异步和批量执行状态更新以优化性能.因此,您永远不能相信在调用 setState 后要更新的状态.但是你能相信 React 会以与 setState 被调用 for

I know that React may perform state updates asynchronously and in batch for performance optimization. Therefore you can never trust the state to be updated after having called setState. But can you trust React to update the state in the same order as setState is called for

  1. 相同的组件?
  2. 不同的组件?

考虑单击以下示例中的按钮:

Consider clicking the button in the following examples:

1. 是否有可能 a 为假而 b 为真:

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = { a: false, b: false };
  }

  render() {
    return <Button onClick={this.handleClick}/>
  }

  handleClick = () => {
    this.setState({ a: true });
    this.setState({ b: true });
  }
}

2. 是否有可能 a 为假而 b 为真:

class SuperContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { a: false };
  }

  render() {
    return <Container setParentState={this.setState.bind(this)}/>
  }
}

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = { b: false };
  }

  render() {
    return <Button onClick={this.handleClick}/>
  }

  handleClick = () => {
    this.props.setParentState({ a: true });
    this.setState({ b: true });
  }
}

请记住,这些是我的用例的极端简化.我意识到我可以以不同的方式做到这一点,例如在示例 1 中同时更新两个状态参数,以及在示例 2 中对第一个状态更新的回调中执行第二个状态更新.但是,这不是我的问题,我只对是否有React 执行这些状态更新的定义明确的方式,仅此而已.

Keep in mind that these are extreme simplifications of my use case. I realize that I can do this differently, e.g. updating both state params at the same time in example 1, as well as performing the second state update in a callback to the first state update in example 2. However, this is not my question, and I am only interested in if there is a well defined way that React performs these state updates, nothing else.

非常感谢文档支持的任何答案.

Any answer backed up by documentation is greatly appreciated.

推荐答案

我在 React 工作.

I work on React.

TLDR:

但是你能相信 React 会按照调用 setState 的顺序更新状态吗

But can you trust React to update the state in the same order as setState is called for

  • 相同的组件?

是的.

  • 不同的组件?

是的.

始终遵守更新的顺序.您是否看到中间状态介于"之间它们与否取决于您是否在批次内.

The order of updates is always respected. Whether you see an intermediate state "between" them or not depends on whether you're inside in a batch or not.

目前(React 16 及更早版本),默认情况下仅对 React 事件处理程序内部的更新进行批处理.有一个不稳定的 API 可以在您需要时在极少数情况下强制在事件处理程序之外进行批处理.

Currently (React 16 and earlier), only updates inside React event handlers are batched by default. There is an unstable API to force batching outside of event handlers for rare cases when you need it.

在未来的版本中(可能是 React 17 及更高版本),React 默认会批量更新所有更新,所以你不必考虑这个.与往常一样,我们将在 React 博客 和发行说明中宣布对此的任何更改.

In future versions (probably React 17 and later), React will batch all updates by default so you won't have to think about this. As always, we will announce any changes about this on the React blog and in the release notes.

理解这一点的关键是无论在 React 事件处理程序中在多少个组件中调用了多少setState(),它们都会产生仅在事件结束时重新渲染一次.这对于大型应用程序中的良好性能至关重要,因为如果 ChildParent 在处理点击事件时分别调用 setState()想要重新渲染 Child 两次.

The key to understanding this is that no matter how many setState() calls in how many components you do inside a React event handler, they will produce only a single re-render at the end of the event. This is crucial for good performance in large applications because if Child and Parent each call setState() when handling a click event, you don't want to re-render the Child twice.

在您的两个示例中,setState() 调用发生在 React 事件处理程序中.因此,它们总是在事件结束时一起刷新(并且您看不到中间状态).

In both of your examples, setState() calls happen inside a React event handler. Therefore they are always flushed together at the end of the event (and you don't see the intermediate state).

更新总是按照它们发生的顺序浅合并.所以如果第一次更新是{a: 10},第二次是{b: 20},第三次是{a: 30}>,渲染状态将为 {a: 30, b: 20}.对相同状态键的最近更新(例如在我的示例中像 a)总是获胜".

The updates are always shallowly merged in the order they occur. So if the first update is {a: 10}, the second is {b: 20}, and the third is {a: 30}, the rendered state will be {a: 30, b: 20}. The more recent update to the same state key (e.g. like a in my example) always "wins".

当我们在批处理结束时重新渲染 UI 时,会更新 this.state 对象.因此,如果您需要根据以前的状态更新状态(例如增加计数器),您应该使用功能性的 setState(fn) 版本,它为您提供以前的状态,而不是从 this.state.如果您对此原因感到好奇,我在此评论中对其进行了深入解释 .

The this.state object is updated when we re-render the UI at the end of the batch. So if you need to update state based on a previous state (such as incrementing a counter), you should use the functional setState(fn) version that gives you the previous state, instead of reading from this.state. If you're curious about the reasoning for this, I explained it in depth in this comment.

在您的示例中,我们不会看到中间状态"因为我们在启用批处理的 React 事件处理程序中(因为 React 知道"我们何时退出该事件).

In your example, we wouldn't see the "intermediate state" because we are inside a React event handler where batching is enabled (because React "knows" when we're exiting that event).

然而,在 React 16 和更早版本中,在 React 事件处理程序之外默认没有批处理.因此,如果在您的示例中我们有一个 AJAX 响应处理程序而不是 handleClick,那么每个 setState() 都会在发生时立即处理.在这种情况下,是的,您看到一个中间状态:

However, both in React 16 and earlier versions, there is yet no batching by default outside of React event handlers. So if in your example we had an AJAX response handler instead of handleClick, each setState() would be processed immediately as it happens. In this case, yes, you would see an intermediate state:

promise.then(() => {
  // We're not in an event handler, so these are flushed separately.
  this.setState({a: true}); // Re-renders with {a: true, b: false }
  this.setState({b: true}); // Re-renders with {a: true, b: true }
  this.props.setParentState(); // Re-renders the parent
});

我们意识到行为因您是否在事件处理程序中而有所不同,这很不方便.这将在未来的 React 版本中更改,默认情况下将批处理所有更新(并提供选择加入的 API 以同步刷新更改).在我们切换默认行为之前(可能在 React 17 中),您可以使用一个 API 来强制批处理:

We realize it's inconvenient that the behavior is different depending on whether you're in an event handler or not. This will change in a future React version that will batch all updates by default (and provide an opt-in API to flush changes synchronously). Until we switch the default behavior (potentially in React 17), there is an API you can use to force batching:

promise.then(() => {
  // Forces batching
  ReactDOM.unstable_batchedUpdates(() => {
    this.setState({a: true}); // Doesn't re-render yet
    this.setState({b: true}); // Doesn't re-render yet
    this.props.setParentState(); // Doesn't re-render yet
  });
  // When we exit unstable_batchedUpdates, re-renders once
});

内部 React 事件处理程序都被包裹在 unstable_batchedUpdates 中,这就是它们默认批处理的原因.请注意,在 unstable_batchedUpdates 中包装更新两次无效.当我们退出最外层的 unstable_batchedUpdates 调用时,更新会被刷新.

Internally React event handlers are all being wrapped in unstable_batchedUpdates which is why they're batched by default. Note that wrapping an update in unstable_batchedUpdates twice has no effect. The updates are flushed when we exit the outermost unstable_batchedUpdates call.

该 API不稳定";从某种意义上说,我们将在默认情况下已启用批处理时将其删除.但是,我们不会在次要版本中删除它,因此如果您需要在 React 事件处理程序之外的某些情况下强制批处理,您可以放心地依赖它直到 React 17.

That API is "unstable" in the sense that we will remove it when batching is already enabled by default. However, we won't remove it in a minor version, so you can safely rely on it until React 17 if you need to force batching in some cases outside of React event handlers.

总而言之,这是一个令人困惑的话题,因为默认情况下 React 仅在事件处理程序中进行批处理.这将在未来版本中改变,届时行为将更加直接.但解决方案不是批量减少,而是默认批量.这就是我们要做的.

To sum up, this is a confusing topic because React only batches inside event handlers by default. This will change in future versions, and the behavior will be more straightforward then. But the solution is not to batch less, it's to batch more by default. That's what we're going to do.

这篇关于React 是否保持状态更新的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆