调用此组件时,出现以下错误。
setState(...):在现有状态转换期间无法更新(例如 在
render
或其他组件的构造函数中)。渲染方法 应该是道具和国家的纯粹功能;构造函数的副作用 是一种反模式,但可以移到componentWillMount
。
似乎是因为{ this.renderCurrentAthlete() }
内部渲染。当我打电话给renderCurrentAthlete
时,我试图通过运行this.setState({ currentAthlete: currentAthleteData.Athlete })
让状态知道当前运动员是谁,但这会导致错误。有关如何妥善处理此事的任何建议?关于该组件的任何其他建议也将是非常棒的!学习如此所有信息都是一个很好的帮助:)
class MiniGame extends Component {
constructor(props){
super(props);
this.state = {
score: 0,
currentAthlete: null
}
}
gameData = [
{Athlete: "Peyton Manning", Img: "someURL"},
{Athlete: "Tony Hawk", Img: "someURL"},
{Athlete: "Tomy Brady", Img: "someURL"},
{Athlete: "Usain Bolt", Img: "someURL"}
]
renderGameButtons() {
return(
<div>
{this.gameData.map((x) => {
return(
<div key={x.Athlete}>
<button className="btn btn-outline-primary" onClick={ () => this.answerHandler(x.Athlete)}> {x.Athlete} </button>
</div>
)
})}
</div>
)
}
renderCurrentAthlete() {
const currentAthleteData = this.gameData[Math.floor(Math.random() * 4)];
//console.log(currentAthleteData);
const imgUrl = currentAthleteData.Img;
const athleteName = currentAthleteData.Athlete;
console.log(imgUrl, athleteName);
//console.log(currentAthlete);
this.setState({ currentAthlete: currentAthleteData.Athlete });
return(
<img className="card-img-top imgCard" src={imgUrl} alt="..."></img>
)
}
answerHandler(answer){
// console.log(a)
// console.log(this.state.currentAthlete)
if(answer === this.state.currentAthlete) {
this.setState({score: this.state.score + 10})
console.log(this.state.score);
}
}
render(){
return(
<div className="miniGameContainer">
<div className="card card-outline-info mb-3">
{ this.renderCurrentAthlete() }
<div className="card-block">
<p className="card-text">Pick your Answer Below</p>
{ this.renderGameButtons() }
</div>
</div>
</div>
)
}
}
答案 0 :(得分:1)
添加方法componentWillMount将此代码放入其中并从renderCurrentAthlete中删除。方法componentWillMount将在render之前调用。查看更多react lifecycle
componentWillMount() {
const currentAthleteData = this.gameData[Math.floor(Math.random() * 4)];
//console.log(currentAthleteData);
const imgUrl = currentAthleteData.Img;
const athleteName = currentAthleteData.Athlete;
console.log(imgUrl, athleteName);
//console.log(currentAthlete);
this.setState({ currentAthlete: currentAthleteData.Athlete });
}