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

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

问题描述

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

链接到 JSfiddle

var Hello = React.createClass({渲染:函数(){返回 (<div><div>你好{this.props.name}</div><复选框/>

);}});var CheckBox = React.createClass({getInitialState:函数(){返回 {亚历克斯:0};},handleChange:函数(事件){this.setState({值:事件.目标.值});this.setState({亚历克斯:5});},渲染:函数(){警报('渲染');返回 (<div><label htmlFor="alex">亚历克斯</label><input type="checkbox" onChange={this.handleChange} name="alex"/><div>{this.state.alex}</div>

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

如您所见,每次渲染时都会弹出一个提示渲染".

你对它为什么能正常工作有解释吗?

解决方案

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

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

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.

Link to a 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 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.

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天全站免登陆