Answer the question
In order to leave comments, you need to log in
Explain behind setState and increment?
class Comp extends React.Component {
state = {
counter: 0
}
render() {
return (
<div>
<strong onClick={()=>{this.setState({counter: ++this.state.counter})}}>Кликни сюда</strong>
<p>Кол-во кликов {this.state.counter}</p>
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
Calling setState replaces the old state object with the new one. Changes in both cases you make in the old one.
The prefix increment works because the value increased by one is passed to the setState call, the postfix increment returns the value before the increment.
In any case, it is wrong to mutate the state object, it is against the ideology of react and can cause errors in other places.
Correct option:
Finally, I will add that it is not equivalent to . Prefix increment is equivalent to writing:
or:
Postfix, something like this:++this.state.counter
this.state.counter + 1
(this.state.counter = this.state.counter + 1, this.state.counter - 1)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question