我试图使用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