我正在学习如何使用 ReactJS、Spotify API 和 Promise。我正在尝试在 Spotify 上获取音乐家的顶级专辑并播放 30 秒的轨道。
我正在使用名为 spotify-web-api-node 的 Spotify 软件包我认为我不了解 React 或 JS 的一些基本知识。 语法错误:意外的 token ,预期 ( (11:8)
从'react'导入React;
import SpotifyWebApi from 'spotify-web-api-node';
require('dotenv').config();
export default class SpotifyComponent extends React.Component {
// Create the api object with the credentials
const spotifyApi = new SpotifyWebApi({
clientId : process.env.REACT_APP_SPOTIFY_CLIENT_ID,
clientSecret : process.env.REACT_APP_SPOTIFY_CLIENT_SECRET
});
// Save the access token so that it's used in future calls
componentDidMount() {
**(11:8)** --> return spotifyApi = new Promise((resolve, reject) => {
spotifyApi.clientCredentialsGrant()
.then( => (data) {
console.log('The access token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
});
// using Promises through Promise, Q or when - get Elvis' albums in range [20...29]
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', {limit: 10, offset: 20})
.then(function(data) {
console.log('Album information', data);
}, function(err) {
console.error(err);
});
});
SpotifyWebApi.setPromiseImplementation(Q);
}
}
最佳答案
您使用 spotify-api
提供的 promise 的方式是正确的。但是,您不应从 componentDidMount
返回 Promise
。 React
对它没有任何用处。
相反,只需在 componentDidMount
中运行基于 promise 的函数即可。
componentDidMount() {
// the next line will actually trigger the promise to run
spotifyApi.clientCredentialsGrant()
.then((data) => { // this line was missing "=>" in your original code
console.log('The access token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
});
// the next line also triggers a promise to run
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', {limit: 10, offset: 20})
.then(function(data) {
console.log('Album information', data);
}, function(err) {
console.error(err);
});
}
您还可以在导入后立即将 Q
设置为 promise 提供者。
import SpotifyWebApi from 'spotify-web-api-node';
SpotifyWebApi.setPromiseImplementation(Q);
关于javascript - ReactJS componentDidMount、Fetch Spotify API 和 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120075/