2016-01-27 23 views
1

我正在用React創建一個Github問題查看器。如何將json值傳遞到React組件

我有一個組件設置回購,然後我想創建單獨的組件來獲取問題的名稱,編號,登錄等。這些組件將最終在主要組件/視圖中使用。我有點卡住了,下面是我到目前爲止。

var GetRepo = React.createClass({ 
getRepo: function(){ 
    var issues = $.getJSON('https://api.github.com/repos/facebook/react/issues', function (data) { 
    }) 
}, 
render: function() { 
    return <div>My repo: {this.props.repo}</div> 
} 

}); 

ReactDOM.render(<GetRepo repo="facebook/react/issues" />, document.getElementById('main')); 


var IssueName = React.createClass({ 
}); 
//IssueName gets the data.title (the issue name) using repo GetRepo 

var IssueNumber = React.createClass({ 
}); 

//IssueNumber gets the data.number (the issue number) using repo from GetRepo 
+0

什麼是你的問題?你卡在哪裏? – Nicholas

+0

可能的重複[在加載數據之前如何防止組件呈現?](http://stackoverflow.com/questions/33131542/how-can-i-prevent-a-component-from-rendering-before-數據被加載) – Mathletics

+0

這不是一個完全重複的問題,但我認爲這種類型的問題最容易通過容器組件解決方案解決。 – Mathletics

回答

1

當然不這樣做的唯一途徑,但下面應該工作:

var GetRepo = React.createClass({ 

    getInitialState: function() { 
     return { 
      repo: {} 
     }; 
    }, 

    componentDidMount: function(){ 
     var that = this; 
     var issues = $.getJSON('https://api.github.com/repos/facebook/react/issues', function (data) { 
      that.setState({ 
       repo: data 
      }); 
     }); 
    }, 

    render: function() { 
     return (
      <div> 
       <IssueName repo={this.state.repo} /> 
       <IssueNumber repo={this.state.repo} /> 
      </div> 
     ); 
    } 
}); 


//IssueName gets the data.title (the issue name) using repo GetRepo 
var IssueName = React.createClass({ 
    render: function() { 
     return (
      <div>this.props.repo.title</div> 
     ); 
    } 
}); 

//IssueNumber gets the data.number (the issue number) using repo from GetRepo 
var IssueNumber = React.createClass({ 
    render: function() { 
     return (
      <div>this.props.repo.number</div> 
     ); 
    } 
}); 

ReactDOM.render(<GetRepo repo="facebook/react/issues" />, document.getElementById('main')); 
+0

我想你應該在某處調用'getRepo'方法,可能在'componentDidMount'中。 – pawel

+0

@pawel是的。謝謝:) – Nam

+0

謝謝,這是有幫助的。但是,它將text.props.repo.title和this.props.repo.number作爲文本輸出。似乎我需要解析JSON數據? – essjay

相關問題