我試圖使用componentDidMount
將JSON訂閱源加載到我的React組件中。當我最初拉動JSON feed時,所有事情都會檢查出來,我可以看到JSON數據很好。當我嘗試深入JSON數據以獲取遊戲信息時,存在這個問題,我開始得到undefined
錯誤。使用React返回的JSON請求undefined
這裏是我的陣營JS:
var MLBScores = React.createClass({
getInitialState: function() {
return {
hometeam: '',
awayteam: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.feed, function(result) {
var scoreFeed = result;
var homeTeamName = scoreFeed.games.game[0].home_team_name;
console.log(homeTeamName);
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (<div> {
this.state.hometeam
}
vs. {
this.state.awayteam
} < /div>
);
}
});
ReactDOM.render(< MLBScores feed= "https://raw.githubusercontent.com/erwstout/pinetar/develop/src/client/app/mlb-scoreboard.json"/> ,
document.getElementById('container')
);
值得一提的是,如果我只是註釋掉var homeTeamName
線,改變console.log(homeTeamName)
到console.log(result);
它打印JSON數據。
在移植到React之前,我已經充實了一些數據(以及我的想法),因此我非常熟悉json文件的結構。所以我想知道它是否與我在React中打電話有關?這是我第一次使用React,所以它可能是我錯過了一些東西。在我的codepen中,我得到每個遊戲的數據,但是爲了在React中測試它,我只是試圖獲得game[0]
信息。
我有一個JS Fiddle of the React code as well。任何幫助,將不勝感激。我一直跟着React Documentation一點點到達這一點,但我迷路了。謝謝!
謝謝那麼多,那有效! – buschschwick