嗯,我的单页应用程序中有一个 View 是测验,但是当单击根据我的数组状态信息通过循环生成组件时,他不会渲染它。我在index.js 中使用react-router 也许这些信息可以提供帮助。
Gabarito.js
return(
<div>
<h1 className="display-1">Resposta-#{this.props.chave}-
{this.props.alternativa}</h1>
</div>);
测验
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}/>));
}
函数渲染
<div className="row justify-content-center">
<span id="teste">{this.state.novogabarito}</span>
</div>
</div>
);
}
}
最佳答案
也许我忽略了一些事情......但看起来你并没有调用过你的alterarevento
和gerargabarito
功能。因此,当您调用eachcomponent
时您所在州的 correcao 数组 仍然为空,因此您没有映射任何内容。
在 eachcomponent
中的返回声明之前函数,尝试记录 correcao
到控制台查看它是否为空。
警告一句:您永远不应该直接操纵您的状态。所以,你的this.state.correcao.push('Certa');
行应该是:
this.setState({ correcao: [...this.state.correcao, 'Certa'] });
关于javascript - React子组件循环不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53683140/