2016-04-15 92 views
0

我试图使用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一点点到达这一点,但我迷路了。谢谢!

回答

1

返回值是一个字符串,而不是对象。修改这个让你的主队名 var scoreFeed = JSON.parse(result).data;

,或者你使用的getJSON()

+0

谢谢那么多,那有效! – buschschwick

0

我没下潜太深到您的JSON响应,但三元可以帮助..

var homeTeamName = 
scoreFeed.games && scoreFeed.games.game[0]scoreFeed ? scoreFeed.games.game[0].home_team_name : 
null