2017-07-30 123 views
1

当调用此组件时,我得到跟随错误。React - setState errir - 在状态转换期间无法更新

的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

你为什么要为SETSTATE currentAthlete,你使用它 –

+0

它似乎并不喜欢在渲染块,因为自动响应状态转换我没有看到通过状态更新DOM ,并在渲染中设置状态可能不是一件好事。也许试试把this.renderCurrentAthlete放到一个像componentDidMount()或者它所建议的那样的反应生命周期方法中,然后从该生命周期方法调用this.renderCurrentAthlete()? –

回答

1

Add方法componentWillMount把这个代码,并从中renderCurrentAthlete删除。方法componentWillMount将在渲染前调用。查看更多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 }); 
} 
+0

谢谢,我昨天晚上看了看,但没有任何意义,但今天早上我回来了,看到了你的回应,并得到了它的工作哈哈。我打算清理一些东西,但是这是我最终完成的工作。 https://hastebin.com/edewajiqus.js – SirFry

相关问题