[英]ReactJS componentDidMount, Fetch Spotify API and Promise
我正在學習如何使用ReactJS,Spotify API和Promise。 我正在嘗試在Spotify上獲取音樂家熱門專輯並播放30秒的曲目。
我正在使用一個名為spotify-web-api-node的Spotify軟件包,我想我不了解React或JS的基本內容。 Syntax error: Unexpected token, expected ( (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
提供的承諾的方式是正確的。 但是,您不應該從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
設置為承諾提供商。
import SpotifyWebApi from 'spotify-web-api-node';
SpotifyWebApi.setPromiseImplementation(Q);
你不能在類這樣的類中有一個const
定義。
您應該將其移到外面或刪除const
:
// 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
});
export default class SpotifyComponent extends React.Component {
要么
export default class SpotifyComponent extends React.Component {
// Create the api object with the credentials
spotifyApi = new SpotifyWebApi({
clientId : process.env.REACT_APP_SPOTIFY_CLIENT_ID,
clientSecret : process.env.REACT_APP_SPOTIFY_CLIENT_SECRET
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.