在我的应用中,
class App extends Component {
constructor(props){
super(props)
this.state={
count:0
}
}
render() {
return (
<div className='App-header'>
<button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>
</div>
)
}
}
我在这个按钮上添加了一个事件:
<button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>
但是当我点击它时,count 的值没有增加
ps:我是新手
最佳答案
与 react 和状态管理相比,这更多地与普通的旧 javascript 有关。
以下是您的问题的小复制:
let y = 2;
y = y++;
console.log(y);
y = ++y;
console.log(y);
这是因为 ++
[(increment operator)](如果使用后缀,运算符在操作数之后(例如,x++),increment operator 递增并返回递增前的值。 ) 有效。
来自文档:
If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.
另外值得注意的是,你不应该做这样的事情:
this.state.variable = randomValue;
修复
this.setState({count:this.state.count=++this.state.count})
会工作因为
this.state.count=++this.state.count
返回增量计数。但是状态实际上是由 this.setState
更新的,你也可以这样做:
this.setState({count:++this.state.count})
关于javascript - 状态中的计数值不递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72744313/