【发布时间】:2020-10-04 09:09:00
【问题描述】:
我已经开始学习 react 使用官方文档遇到了这个“React 可能将多个 setState() 调用批处理到单个更新中以提高性能。因为 this.props 和 this.state 可能会异步更新,所以你不应该依赖它们用于计算下一个状态的值。”在实践中,我遇到了这个问题,我认为这在某种程度上与此有关,但我仍然不明白为什么 sn-p(1) 不起作用而 sn-p(2) 起作用。
// code-snippet(1)
import React from "react";
import ReactDOM from 'react-dom';
import "./styles.css";
class Count extends React.Component {
constructor(props) {
super(props);
this.state = {count : 0};
}
increment() {
var newCount = state.count + 1;
this.setState({count: newCount});
}
increment5() {
this.increment();
this.increment();
this.increment();
this.increment();
this.increment();
}
render() {
return (
<div>
<h1>Count - {this.state.count}</h1>
<button onClick={() => this.increment5()}>Increment</button>
</div>
);
}
}
ReactDOM.render(<Count />, document.getElementById("root"));
// code-snippet(2)
import React from "react";
import ReactDOM from 'react-dom';
import "./styles.css";
class Count extends React.Component {
constructor(props) {
super(props);
this.state = {count : 0};
}
increment() {
this.setState(function(state) {
var newCount = state.count + 1;
return {count : newCount};
});
}
increment5() {
this.increment();
this.increment();
this.increment();
this.increment();
this.increment();
}
render() {
return (
<div>
<h1>Count - {this.state.count}</h1>
<button onClick={() => this.increment5()}>Increment</button>
</div>
);
}
}
ReactDOM.render(<Count />, document.getElementById("root"));
【问题讨论】:
标签: javascript reactjs rxjs state setstate