我想检查多次使用this.setState时会发生什么(为讨论起见,这是2次).我认为该组件将呈现两次,但显然它只呈现一次.我的另一个期望是,对于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')
);
Run Code Online (Sandbox Code Playgroud)
正如您将看到的,每次渲染都会弹出一个"渲染"警告.
你有解释为什么它正常工作?
对于类组件,this.setState
如果在事件处理程序内部则调用批处理.但是如果在事件处理程序之外更新状态并使用'useState'钩子会发生什么?
function Component() {
const [a, setA] = useState('a');
const [b, setB] = useState('b');
function handleClick() {
Promise.resolve().then(() => {
setA('aa');
setB('bb');
});
}
return <button onClick={handleClick}>{a}-{b}</button>
}
Run Code Online (Sandbox Code Playgroud)
它会useState
马上渲染吗?或者它会是aa - bb
然后aa - b
呢?