.map不是React函数

时间:2016-05-07 01:47:11

标签: jquery json ajax reactjs jsx

我正在开发一个小应用程序,它将从JSON文件中提取一些数据(游戏分数)。目前我收到错误games.map is not a function。我在Stack Overflow上看到了另一篇类似的帖子,但答案是初始状态不是数组,但我将初始状态设置为数组,所以我不相信它适用。以下是我的React JS,有人能指出我正确的方向吗?它可能与JSON结构有关吗?您可以找到json文件here。谢谢你!

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')
);

1 个答案:

答案 0 :(得分: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)
    });
  }