Map函数没有't迭代所有子项

Map function doesn't iterate all children

本文关键字:迭代 函数 Map      更新时间:2023-09-26

我正在为一个应用程序构建一个侧边栏,它由较小的元素组成。现在遇到了一个问题,即侧边栏子元素数组没有完全迭代,尽管每个子元素都由一个唯一的键组成。我觉得这可能和钥匙有关

边栏元素组件:

var AppSidebar = React.createClass({
  getInitialState: function() {
    return {
      children: []
    };
  },
  getPlaylists: function() {
    var that = this;
    // returns array of objects
    spotify.getMePlaylists(function(err, playlists) {
      if(err)
        console.error(err);
      that.setState({
        children: playlists
      });
    });
  },
  componentDidMount: function() {
    this.getPlaylists();
  },
  render: function() {
    // iterates all children
    this.state.children.map(function(playlist) {
      console.log(1, playlist.id, playlist.name);
    });
    var playlists = this.state.children;
    return (
      <div id="sidebar">
        playlists.map(function(playlist) {
          // only returns first playlist id and name
          console.log(2, playlist.id, playlist.name);
          return (<AppSidebarElement key={playlist.id} {...playlist} />);
        })}
      </div>
    );
  }
});

边栏组件:

var AppSidebarElement = React.createClass({
  render: function() {
    return (
      <div className="playlist">
        {this.props.name}
      </div>
    );
  }
});

控制台输出:

1 "75dwLdmL07hDEDWqX17QeE" "The Indie Mix"
1 "2wOXCZ6fJAjpekKlnbg49F" "Interesting artists"
1 "6ULfvJbsdzF7u14dBZo9w1" "chsshhh"
1 "4LJ5hkgqt04IKw454SUJqV" "Motivational Songs"
1 "75if3ukZz2tPS60IVMPhw6" "Best of the Suits Soundtrack"
...
2 "69H6RgTVs1jrv1IuuLe1a5" "Deep Dark Indie"

问题是由我在将其发布到堆栈溢出时清理的代码引起的,它与在映射函数上下文中调用错误的this有关。