![](/img/trans.png)
[英]Spotify Web API: Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
[英]TypeError: Cannot read property of undefined while using spotify's api
我正在嘗試將 spotify 的 API 鏈接到我的應用程序,但是當我嘗試運行代碼時,出現以下錯誤:
這是代碼:首先,我使用useEffect
來放置腳本標簽並鏈接 API,然后,我聲明了 var Spotify
,但是當頁面加載時,它沒有在Spotify
找到屬性Player
import React, { useEffect } from 'react' function SpotifyPlayer() { var Spotify:any useEffect(() => { const script = document.createElement('script'); script.src = "https://sdk.scdn.co/spotify-player.js"; script.async = true; document.body.appendChild(script); return () => { document.body.removeChild(script); } }, []); (window as any).onSpotifyWebPlaybackSDKReady = () => { const token = '[token]'; const player = new Spotify.Player({ name: 'Web Playback SDK Quick Start Player', getOAuthToken: (cb:any) => { cb(token); } }); // Error handling player.addListener('initialization_error', ({message}:any ) => { console.error(message); }); player.addListener('authentication_error', ({ message }:any) => { console.error(message); }); player.addListener('account_error', ({ message }:any) => { console.error(message); }); player.addListener('playback_error', ({ message }:any) => { console.error(message); }); // Playback status updates player.addListener('player_state_changed', (state:any) => { console.log(state); }); // Ready player.addListener('ready', ({ device_id }:any) => { console.log('Ready with Device ID', device_id); }); // Not Ready player.addListener('not_ready', ({ device_id }:any) => { console.log('Device ID has gone offline', device_id); }); // Connect to the player! player.connect(); }; return <h1>Spotify Player</h1> } export default SpotifyPlayer
-> 我也在使用 React。
您為 Spotify any
打字沒有任何屬性。 ;) 最好的辦法是檢查 Spotify 是否有類型庫並在此處使用它。 否則,您可以使用具有您指向的屬性的類型。
type SpotifyType {
properties: any; // better to look for the typing config
}
var Spotify:SpotifyType
另一種選擇是嘗試!
非空斷言
const player = new Spotify!.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: (cb:any) => { cb(token); }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.