【问题标题】:.map is not a function React.map 不是函数 React
【发布时间】:2016-09-02 04:37:59
【问题描述】:

我正在开发一个小型应用程序,该应用程序将从 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')
);

【问题讨论】:

  • 可以先登录游戏再返回吗?
  • data 似乎是一个对象,而不是一个数组
  • 是的,看起来它返回一个object,然后在里面是一个游戏对象数组。所以我想现在的问题变成了如何访问这些对象?你可以在这里看到console.log 截图:prnt.sc/b175rh@JordanHendrix
  • 是的,你没有得到游戏数组...请参阅下面的答案:

标签: jquery json ajax reactjs jsx


【解决方案1】:

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

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

【讨论】:

  • 你先生,刚刚度过了我的周末。我还在学习反应,所以我很感激你抽出时间来帮忙。干杯!
  • 随时!我们都很乐意提供帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 2020-09-20
  • 2020-07-26
  • 1970-01-01
相关资源
最近更新 更多