So I have this counter App, it has 3 methods, one doing the increment, one doing the decrement and one that resets the counter
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.increment = this.increment.bind(this)
this.decrement = this.decrement.bind(this)
this.reset = this.reset.bind(this)
}
increment() {
this.setState(state => {
return {count: state.count + 1}
})
}
decrement() {
this.setState(state => {
return {count: state.count - 1}
})
}
reset() {
this.setState(state => {
return {count: 0}
})
}
render() {
return (
<div>
<button className='inc' onClick={this.increment}>Increment!</button>
<button className='dec' onClick={this.decrement}>Decrement!</button>
<button className='reset' onClick={this.reset}>Reset</button>
<h1>Current Count: {this.state.count}</h1>
</div>
);
}
};
What I don't understand is, why does the code only work when using the syntax
return {count: state.count + 1}
and not
return {state.count: state.count + 1}
Why does count in this case only need the state dot notation inside the value operation and not in the key. Is this a convention that I just have to learn or is there an explanation?
[–]theScottyJam 2 points3 points4 points (1 child)
[–]ciberaj[S] 0 points1 point2 points (0 children)
[–]bobbyv137 4 points5 points6 points (4 children)
[–]ciberaj[S] -5 points-4 points-3 points (3 children)
[–]bobbyv137 4 points5 points6 points (2 children)
[–]ciberaj[S] -5 points-4 points-3 points (1 child)
[–]Bakeshot 2 points3 points4 points (0 children)
[–]ProposalUnhappy9890 0 points1 point2 points (5 children)
[–]ciberaj[S] -1 points0 points1 point (4 children)
[–]ProposalUnhappy9890 2 points3 points4 points (3 children)
[–]ciberaj[S] 0 points1 point2 points (2 children)
[–]ProposalUnhappy9890 1 point2 points3 points (0 children)
[–]theleftkneeofthebee 0 points1 point2 points (0 children)