Nathan Aguiar Neves
Nathan Aguiar Neves

Reputation: 11

React Child Component Loop not redenring

Well I have one of the views from my single page application that is a Quiz, But when a click to generate the Components through a loop based on information on my array state he doesn't render it. I'm using react-router in the index.js maybe this information can help.

Gabarito.js

 return(
      <div>
    <h1 className="display-1">Resposta-#{this.props.chave}- 
     {this.props.alternativa}</h1>
    </div>);

Quiz

state = {       
    respostas:[10],
    gabarito:['Verdadeiro','Falso','Falso','Verdadeiro','Verdadeiro','Falso','Verdadeiro','Falso','Verdadeiro','Verdadeiro'],
    correcao:[],
    novogabarito: this.eachcomponent


  }
  alterarevento = (evento,index) =>{
      let array = this.state.respostas;
      array[index] = evento.target.value;
      this.setState({respostas:array}); 
      console.log(this.state.respostas[index])

  }
  gerargabarito = () =>{
    for(let n=0;n<10;n++){
        if(this.state.respostas[n]===this.state.gabarito[n]){
            this.state.correcao.push('Certa');
        }
        else{
           this.state.correcao.push('Errada');
        }
    }
    console.log(this.state.correcao);
  }
  eachcomponent = () =>{
    return(this.state.correcao.map(resposta=><Gabarito chave={this.state.correcao.indexOf(resposta)} alternativa={resposta}/>));

  }

Render of function

<div className="row justify-content-center">
                <span id="teste">{this.state.novogabarito}</span>
            </div>

        </div>
     );
}
 }   

Upvotes: 0

Views: 31

Answers (1)

Bens Steves
Bens Steves

Reputation: 2849

Perhaps I am overlooking something...but it does not look like you are ever invoking your alterarevento and gerargabarito functions. So when you call your eachcomponent your correcao array in your state is still empty so you are not mapping anything.

Before your return statement in your eachcomponent function, try logging correcao to the console to see if it is empty.

A word of caution: you should never manipulate your state directly. So, your this.state.correcao.push('Certa');

line should be:

this.setState({ correcao: [...this.state.correcao, 'Certa'] });

Upvotes: 1

Related Questions