2016-05-07 90 views
0

我正在研究一个从JSON文件(游戏成绩)中提取一些数据的小应用程序。目前我收到错误games.map is not a function。我看到Stack Overflow上的另一篇帖子很相似,但答案是初始状态不是数组,但我已将初始状态设置为数组,因此我不相信它适用。下面是我的React JS任何人都可以将我指向正确的方向吗?它可能与JSON结构有关吗?你可以找到json文件here。非常感谢你!.map不是函数React

class SingleGame extends React.Component{ 
    render(){ 
    return(
     <div>{this.props.homeTeam}</div> 
    ); 
    } 
} 

class GameBox extends React.Component{ 

    constructor() { 
    super(); 

    this.state = { 
     games: [] 
    }; 
    } 

    componentWillMount() { 
    this._getGameScores(); 
    } 

    componentDidMount() { 
    this._timer = setInterval(() => this._getGameScores(), 45000); 
    } 

    componentWillUnmount() { 
    clearInterval(this._timer); 
    } 

    _getGameScores(){ 
    jQuery.ajax({ 
     method: 'GET', 
     url: 'http://pinetar-app.com/src/client/app/mlb-scoreboard.json', 
     success: function(games){ 
     this.setState({games: games.data}); 
     }.bind(this) 
    }); 
    } 

    _mapGameScores(){ 
    const games = this.state.games; 

    return games.map((games) => { 
     return(
     <SingleGame homeTeam={games.game.home_team_name} /> 
    ); 
    }); 
    } 

    render() { 
    const gameList = this._mapGameScores(); 
    return(
     <div> 
     {gameList} 
     </div> 
    ); 
    } 
} 

ReactDOM.render(
    <GameBox />, document.getElementById('pinetar') 
); 
+0

您可以登录游戏,你回来之前它在? – JordanHendrix

+0

'data'似乎是一个对象,而不是一个数组 –

+0

是的,它看起来像返回一个'object',然后里面是一个对象的游戏数组。所以我想现在的问题变成了如何访问这些对象?你可以在这里看到一个'console.log'的截图:http://prnt.sc/b175rh @JordanHendrix – buschschwick

回答

2

您没有访问数组正确,请尝试使用过的映射:

data.data.games.game 

像这样:

Working example

_getGameScores(){ 
    jQuery.ajax({ 
     method: 'GET', 
     url: 'http://pinetar-app.com/src/client/app/mlb-scoreboard.json', 
     success: function(data){ 
     this.setState({games: data.data.games.game }); 
     }.bind(this) 
    }); 
    } 
+1

你先生,只是让我的周末。我仍然在学习反应,所以我感谢你花时间帮忙。干杯! – buschschwick

+0

任何时候!我们都很乐意提供帮助! – JordanHendrix