K
K
Kappy2018-12-14 11:50:17
JavaScript
Kappy, 2018-12-14 11:50:17

How to update a component depending on a function?

I'm completely confused, please help me figure it out.
There is a form. It uses radiobuttons - buttons, like switches. The active button has the active class. I need to display the degree of completion of the form, each button toggle uses the Set State. I also use refs. My idea is this: State has been changed, there is a life cycle of state change. Called: Component Did Update. We need it because we can get refs from the form here. In it, I count the selected answers, and I want to throw

this.setState({progress:active/((active+overs)/2)*100})

And then the code went into recursion.
Isn't that how the cycle happens:
Press the button, call SetState, call Will Update , render, DidUpdate here we change the state again, where it should just pass the state:
this.setState({progress:active/((active+overs)/2)*100})

I'm a little confused about the life cycle, help me figure it out, thanks in advance!
As far as I understand, it is in will update that the recursion occurs, because setState cannot be called there at all. But then how to get the data from the form and update the state. The only thing that comes to mind is shouldComponentUpdate (state.prev!=state.next)
I decided to go the other way, made a function, when clicking on which we take refs, count and change the state.
progressForm(){
   console.log(this.myRef)
   var active=0;
   var overs=0;
  for(let i=0;i<this.myRef.current.length;i++){
    console.log(this.myRef.current[i].className)
    if (this.myRef.current[i].className.includes('active')){
        active++;
    }
        else if (this.myRef.current[i].className.includes('btn'))
        overs++;
  }
  
  this.setState({progress:active/((active+overs)/2)*100}) 

 
 }

And the bottom line is that the form log displays the form, with an immediately changed state, where the class is active.
And the log in a cycle displays the old data, where the class has not yet changed.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question