在React组件中多次使用this.setState会发生什么? [英] What happens when using this.setState multiple times in React component?

查看:614
本文介绍了在React组件中多次使用this.setState会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查多次使用this.setState时会发生什么(为讨论起见,2次)。
我认为该组件将呈现两次,但显然它只呈现一次。我的另一个期望是,对于setState的第二次调用可能会超过第一次,但你猜对了 - 工作正常。

I wanted to check what happens when you use this.setState multiple times (2 times for the sake of the discussion). I thought that the component will be rendered twice but apparently it's rendered only once. Another expectation I had was that maybe the second call for setState will run over the first one, but you guessed it - worked fine.

链接到 JSfiddle

var Hello = React.createClass({
  render: function() {
    return (
      <div>
        <div>Hello {this.props.name}</div>
        <CheckBox />
      </div>
    );
  }
});

var CheckBox = React.createClass({
  getInitialState: function() {
    return {
      alex: 0
    };
  },

  handleChange: function(event) {
    this.setState({
      value: event.target.value
    });
    this.setState({
      alex: 5
    });
  },

  render: function() {
    alert('render');
    return (
      <div>
        <label htmlFor="alex">Alex</label>
        <input type="checkbox" onChange={this.handleChange} name="alex" />
        <div>{this.state.alex}</div>
      </div>
    );
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

正如您所见,每次渲染都会弹出一个渲染警告。

As you'll see, an alert that says 'render' pops up on every render.

你有解释它运作正常的原因吗?

Do you have an explanation for why it worked properly?

推荐答案

React批处理事件处理程序和生命周期方法中发生的状态更新。因此,如果您在< div onClick /> 处理程序中多次更新状态,React将在重新呈现之前等待事件处理完成。

React batches state updates that occur in event handlers and lifecycle methods. Thus, if you update state multiple times in a <div onClick /> handler, React will wait for event handling to finish before re-rendering.

需要说明的是,这仅适用于React控制的合成事件处理程序和生命周期方法。例如,状态更新不会在AJAX和 setTimeout 事件处理程序中进行批处理。

To be clear, this only works in React-controlled synthetic event handlers and lifecycle methods. State updates are not batched in AJAX and setTimeout event handlers, for example.

这篇关于在React组件中多次使用this.setState会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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