P
P
Paxest2019-04-23 18:48:25
React
Paxest, 2019-04-23 18:48:25

What is the correct way to force a class state update?

Good day!
I needed the counter to change the state value not once, but constantly, because it is known that setState () acts asynchronously.
To do this, I put an empty function so that it updates immediately. I use this kind of entry:

this.setState({ text: this.state.text.slice(0, -1)}, () => {})

Found another way:
this.setState(function(state, props) {
 return {      
   text: this.state.text.slice(0, -1)
 }});

or through the function
// outside your component class
 function increaseScore (state, props) {
    return {score : state.score + 1}
 }
class User{
 …
// inside your component class
 handleIncreaseScore () {
   this.setState( increaseScore)
 }
…
 }

But I would like not to fence the functions every time, and I thought that maybe there is a way to do this through componentWillReceiveProps() and shouldComponentUpdate().
Question: how to forcefully update the state of the class? And can it be done through lifecycle methods?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-23
@Paxest

To solve your problem, you just need to update all the data with one call:

onClick(e) {
  const { value, type } = e.target.dataset;

  this.setState({
    letter: this.state.letter + value,
    lastType: this.state.newType,
    newType: type,
    compareType: type === this.state.newType,
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question