我在使用 React 时遇到的错误:如果您打算渲染子项的集合,请使用数组



所以我要做的是从用户那里获取所有播放列表,这是我在控制台时看到的.log它。但是我收到一个错误,关于使用数组来渲染 getAll 中的播放列表变量的子集合,因为这是我尝试存储它的地方。我对反应和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
}
});
})  
}
render() {
return (
<div className="App">
<a href='http://localhost:8888' > 
<button> Logout </button> 
</a>
<div>
Now Playing: 
{ this.state.nowPlaying.name }
</div>
<div>
Album: 
{ this.state.nowPlaying.albumName }
</div>
<div>
<img src={this.state.nowPlaying.albumArt} style={{ height: 150 }} />
</div>
<ul>
{           
this.state.getAll.map((playlist, index) => (
<li key={index}> { playlist }</li>
))
}
</ul>
{
<button onClick={() => this.getPlaylists()}>
Check Playlists
</button>
}
{ 
this.state.loggedIn &&
<button onClick={() => this.getNowPlaying()}>
Check Now Playing
</button> 
}
</div>
);
}
}
export default App;

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

你能尝试替换...

{this.state.getAll.playlists}

跟。。。

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

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

最新更新