问题描述
为什么当我在做 this.setState({count:this.state.count*2})
时它正在工作,但是当我在做:this.setState({count:this.state.count++})
它不起作用?
Why when I am doing this.setState({count:this.state.count*2})
it is working, but when I am doing: this.setState({count:this.state.count++})
it is not working?
为什么,以及如何解决?
Why, and how to fix it?
完整代码:
var Hello = React.createClass({
getInitialState:function(){
return {count:parseInt(this.props.count)}
},
a:function(){
this.setState({count:this.state.count++})
console.log(this.state)
},
render: function() {
console.log(this.state)
return <div onClick={this.a}>Click to increment the counter<b> {this.state.count} </b></div>;
}
});
ReactDOM.render(
<Hello count="1" />,
document.getElementById('container')
);
但此代码正在运行:
a:function(){
this.setState({count:this.state.count*2})
console.log(this.state)
},
JSFiddle:https://jsfiddle.net/69z2wepo/55100/
推荐答案
通过执行 this.state.count++
,你改变了状态,因为它和执行 this.state 是一样的.count += 1
.你永远不应该改变状态(见 https://facebook.github.io/react/docs/component-api.html).更喜欢这样做:
By doing this.state.count++
, you mutate the state, because it's the same thing than doing this.state.count += 1
. You should never mutate the state (see https://facebook.github.io/react/docs/component-api.html). Prefer to do that instead:
this.setState({ count: this.state.count + 1 })
这篇关于如何在 React 中使用增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!