V
V
vs17102018-08-24 14:01:57
JavaScript
vs1710, 2018-08-24 14:01:57

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>
)
}
}

There is such a code. The question is why the prefix form ++this.state.counter(this.state.counter+1) works, while the postfix form does not change the value in this.state at all. Does it have something to do with how setState works?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-24
@vs1710

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.counterthis.state.counter + 1

(this.state.counter = this.state.counter + 1, this.state.counter - 1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question