2017-02-13 46 views
1

之前運行每當我嘗試從componentWillMount中獲取我的結果時,應用程序首先渲染render(),然後它碰到componentWillMount,獲取我的結果,設置狀態,然後再次點擊渲染。爲什麼我的渲染函數在我的componentWillMount

componentWillMount=() => { 
    let team = gh.getRepo('Microsoft', 'vscode'); 
    team.getContributors(function(err, members){ 
    }).then(response => { 
     this.setState({ 
     data: response.data 
     }); 
    }); 
} 


render() { 
    var ghList = this.state.data; 
    const names = ghList.map(name => { //when it runs the first time this map in invalid since ghList is null from my this.setState= {data:null} 
}) 
return (
     <div className="flip-container" onClick={this.onTileClick}> 
     <div className="flipper"> 
      <div className="front"> 
       <img className="circle" src={this.state.avatar_url} alt={this.state.login}/> 
      </div> 
     <div className="back"> 
     </div> 
     </div> 
     </div> 
) 
+0

你有一個jsfiddle或我們試過的東西嗎? –

+3

建議您使用componentDidMount進行AJAX調用。看到http://stackoverflow.com/questions/27139366/why-do-the-react-docs-recommend-doing-ajax-in-componentdidmount-not-componentwi – ryandrewjohnson

+0

作出改變,謝謝我將它添加到我的開發筆記。 – pcproff

回答

3

如果我理解正確,這是預期的行爲。這是怎麼回事:

  1. componentWillMount():觸發異步請求(getContributors)。
  2. render()第一次,this.state.data = undefined
  3. getContributors的回調被調用(響應已到),然後調用setState:setState調度新的呈現。
  4. 渲染()秒時間,與人口this.state.data

你必須處理您的初始狀態呈現(您的組件將如何在AJAX返回之前渲染:也許有些正在加載的旋轉..) 。因此,在渲染方法中,您可以檢查this.state.data是否爲null/undefined並繞過您的邏輯。或者,在構造函數中,您的數據設置爲空數組:

constructor(props) { 
    super(props); 
    this.state = { 
    data: [] 
    } 
} 

這樣,至少ghList.map不會拋出一個錯誤。

+0

這工作。我有'data:null'而不是null。 – pcproff

相關問題