【发布时间】:2020-06-15 17:08:40
【问题描述】:
虽然我绑定了 getNowPlaying,但我收到以下错误,如果我的代码中缺少某些内容,有人可以帮忙吗?我尝试导入 SpotifyWebApi 的方式是否错误?
这是导致问题的代码:
import React, { Component } from 'react';
import './App.css';
import SpotifyWebApi from 'spotify-web-api-js';
const spotifyApi = new SpotifyWebApi();
class App extends Component {
constructor(props){
super(props);
const params = this.getHashParams();
const token = params.access_token;
if (token) {
spotifyApi.setAccessToken(token);
}
this.state = {
loggedIn: token ? true : false,
nowPlaying: { name: 'Not Checked', albumArt: '' }
}
this.getNowPlaying=this.getNowPlaying.bind(this);
}
getNowPlaying(){
spotifyApi.getMyCurrentPlaybackState()
.then((response) => {
this.setState({
nowPlaying: {
name: response.item.name,
albumArt: response.item.album.images[0].url
}
});
})
}
render() {
return (
<div className="App">
<a href='http://localhost:8888' > Login to Spotify </a>
<div>
Now Playing: { this.state.nowPlaying.name }
</div>
</div>
);
}
}
export default App;
【问题讨论】:
-
尝试
console.log(response)看看response对象有哪些属性 -
我在哪里添加它重要吗?当我在下面的
getNowPlaying(){ console.log(response); spotifyApi.getMyCurrentPlaybackState..中添加它时,它说没有定义响应。 -
是的,添加它的位置很重要,您应该在此行之前添加它
this.setState({,因为getMyCurrentPlaybackState是一个承诺,并且需要在您打印response之前完成它控制台。 -
响应 && response.item.album.images[0].url