我在链接这两个API调用时遇到麻烦。因此,基本上,我试图重新创建Spotify接口,并且这些调用实际上可以正常工作,这很棒!
我还有一个'onPlayClick'函数,与下面的'onNextClick'基本相同,但是具有不同的端点,并且是PUT方法而不是POST方法。那会正确播放并设置selectedSong的状态。
但是,onNextClick调用updateCurrentlyPlaying无法正常工作。预期的功能是,当用户单击下一步时,歌曲将转到下一个曲目(有效!),然后在UI上更新曲目信息。
但是最终发生的事情是,它首先更新了轨道信息,然后切换了轨道,因此在UI上,从某种意义上说,它总是“落后于一条轨道”,我不知道为什么第二个API领先于第一个API一! :S非常感谢您的帮助!
onNextClick = () => {
const { deviceId, token } = this.state
fetch(`https://api.spotify.com/v1/me/player/next?device_id=${deviceId}`, {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token },
})
.then(response => response.json())
.then(this.updateCurrentlyPlaying())
}
updateCurrentlyPlaying(){
const { deviceId, token } = this.state;
let selectedSong;
fetch(`https://api.spotify.com/v1/me/player/currently-playing?device_id=${deviceId}`, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
})
.then(response => response.json())
.then(data => {
selectedSong = {
name: data.item.name,
duration: Math.round(data.item.duration_ms / 1000),
artists: data.item.artists,
album: data.item.album.name,
image: data.item.album.images[0],
id: data.item.id,
uri: data.item.uri,
offset: data.offset
}
this.setState({ selectedSong })
})
}
答案 0 :(得分:0)
如下所述,下面的原始答案可能仍然有用。但是,第一个问题是this.updateCurrentlyPlaying
的调用方式。在编写.then(this.updateCurrentlyPlaying())
时,您将立即调用this.updateCurrentlyPlaying
,这会将undefined
传递回Promise链中。
相反,您需要类似的东西:
onNextClick = () => {
const { deviceId, token } = this.state
fetch(`https://api.spotify.com/v1/me/player/next?device_id=${deviceId}`, {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token },
})
.then(() => this.updateCurrentlyPlaying())
}
我的猜测是您的代码很好,但是Spotify的行为不符合您的期望。当您发布到me/player/next
时,端点会立即响应代码204,表明它已收到您的请求。
实际上,Spotify API docs就是这样:
完成的请求将返回204 NO CONTENT响应代码,然后将命令发布给播放器。
这意味着您的代码会看到204,并立即继续调用当前曲目的Spotify API。这种情况发生在之前已被Spotify的播放器调用的上述command to the player
之前。
我对Spotify API不太熟悉,我看到它是在Beta版中的-也许他们会在不久的将来提供更优雅的解决方案。在此之前,最好的选择是重试第二次通话(有超时限制),直到确认音轨确实已更改为止。
这是一个简单的示例,说明如何实现:
updateCurrentlyPlaying(priorSongId) {
const {deviceId, token} = this.state;
let selectedSong;
let numTries = 0;
const retryFetchUntilUpdate = () => {
fetch(`https://api.spotify.com/v1/me/player/currently-playing?device_id=${deviceId}`, {
method: 'GET',
headers: {'Authorization': 'Bearer ' + token},
})
.then(response => response.json())
.then(data => {
if (data.item.id === priorSongId && numTries < 5) {
numTries += 1;
setTimeout(retryFetchUntilUpdate, 250)
} else {
selectedSong = {
name: data.item.name,
duration: Math.round(data.item.duration_ms / 1000),
artists: data.item.artists,
album: data.item.album.name,
image: data.item.album.images[0],
id: data.item.id,
uri: data.item.uri,
offset: data.offset
}
this.setState({selectedSong})
}
})
}
retryFetchUntilUpdate();
}