我想检查多次使用 this.setState 时会发生什么(为了讨论,两次)。我认为该组件将被渲染两次,但显然它只被渲染一次。我的另一个期望是对 setState 的第二次调用可能会超过第一个,但您猜对了 - 工作正常。
链接到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')
);
如您所见,每次渲染时都会弹出一个提示“渲染”。
你对它为什么正常工作有解释吗?