为了账号安全,请及时绑定邮箱和手机立即绑定

我在 React 上遇到的错误:如果你打算渲染一个子集合,请改用数组

我在 React 上遇到的错误:如果你打算渲染一个子集合,请改用数组

呼唤远方 2022-08-18 09:54:51
因此,我试图做的是从用户那里获取所有播放列表,当我控制台.log它时,我可以看到它正在工作。但是我收到一个关于使用数组来呈现getAll中的播放列表变量的子集合的错误,因为这是我试图存储它的地方。我对 react 和 javascript 很陌生,所以我确信这是一个愚蠢的错误。 class App extends Component {  constructor(){    super();    var list = new Array();    const params = this.getHashParams(); //tokens saved here    const token = params.access_token;    if (token) {      spotifyApi.setAccessToken(token);    }    this.state = {      loggedIn: token ? true : false,      nowPlaying: { name: ' Not Checked', albumArt: '', albumName: ' Nobody'},      getAll: {playlists: []}    };    this.getNowPlaying = this.getNowPlaying.bind(this);    this.getPlaylists = this.getPlaylists.bind(this);  }  getHashParams() { //uses authenticated users refresh and access token    var hashParams = {};    var e, r = /([^&;=]+)=?([^&;]*)/g,        q = window.location.hash.substring(1);    e = r.exec(q)    while (e) {       hashParams[e[1]] = decodeURIComponent(e[2]);       e = r.exec(q);    }    return hashParams;  }  getNowPlaying(){        spotifyApi.getMyCurrentPlaybackState()          .then((response) => {            this.setState({              nowPlaying: {                   name: response.item.name,                   albumArt: response.item.album.images[0].url,                  albumName: response.item.album.name                }            });          })     }  getPlaylists(){    spotifyApi.getUserPlaylists()      .then((response) => {        console.log(response.items)        this.setState({          getAll: {             playlists: response.items           }        });      })    } 
查看完整描述

2 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

React 不会以这种方式工作。你可以这样做


render() {

 return (

   <>

     All playlists:

   <ul>

     {

        this.state.getAll.playlist.map((playlist, index) => (

          <li key={index}> { playlist }</li>

        ))

     }

   </ul>

    <button onClick={() => this.getPlaylists()}>

         Check Playlists

     </button>

 </>

 )

}

此外,您需要在构造函数中绑定所有函数或使用箭头函数。


this.getNowPlaying = this.getNowPlaying.bind(this);


查看完整回答
反对 回复 2022-08-18
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

你能尝试更换...

{this.state.getAll.playlists}

跟。。。

{this.state.getAll.playlists.map(playlist => <div>{playlist}</div>)}

我认为现在您并没有真正迭代播放列表数组。


查看完整回答
反对 回复 2022-08-18
  • 2 回答
  • 0 关注
  • 211 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号