2017-07-30 80 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

相關問題