React是否保持状态更新的顺序?

JavaScript

西门前端

2020-03-11

我知道React可以异步并批量执行状态更新以优化性能。因此,在调用之后,您将永远无法相信要更新的状态setState但是你可以信任的反应更新相同的顺序状态setState被称为

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

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

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 });
  }
}

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.

第826篇《React是否保持状态更新的顺序?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
Eva千羽 2020.03.11

文档中

的setState()入列更改组件状态并告诉阵营,这个组件和它的孩子需要重新渲染与更新的状态。这是用于响应事件处理程序和服务器响应而更新用户界面的主要方法。

它将按照队列中的顺序执行更改(FIFO:先进先出),第一个调用将首先执行

Green老丝Itachi 2020.03.11

同一周期内的多个呼叫可以一起批处理。例如,如果您尝试在同一周期内多次增加项目数量,则将导致以下结果:

Object.assign(
  previousState,
  {quantity: state.quantity + 1},
  {quantity: state.quantity + 1},
  ...
)

https://reactjs.org/docs/react-component.html

村村神无猴子 2020.03.11

这实际上是一个非常有趣的问题,但是答案应该不会太复杂。在媒体上有一篇很棒的文章有答案。

1)如果您这样做

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

我不认为会出现的情况下atruebfalse因为配料

但是,如果b取决于,a则确实可能存在无法获得预期状态的情况。

// assuming this.state = { value: 0 };
this.setState({ value: this.state.value + 1});
this.setState({ value: this.state.value + 1});
this.setState({ value: this.state.value + 1});

处理完上述所有调用后,this.state.value将为1,而不是您期望的3。

在文章中提到了这一点: setState accepts a function as its parameter

// assuming this.state = { value: 0 };
this.setState((state) => ({ value: state.value + 1}));
this.setState((state) => ({ value: state.value + 1}));
this.setState((state) => ({ value: state.value + 1}));

这会给我们 this.state.value === 3

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android