[英]TypeError: Cannot read property of undefined while using spotify's api
I'm trying to link the spotify's API to my app, but when i try to run the code, the following error appears :我正在尝试将 spotify 的 API 链接到我的应用程序,但是当我尝试运行代码时,出现以下错误:
here's the code: First, i use the useEffect
to put the script tag and link the API, then, i declare the var Spotify
, but when the page loads it didn't find the property Player
in Spotify
这是代码:首先,我使用
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
-> I'm using React too. -> 我也在使用 React。
Your typing for Spotify any
doesn't have any properties.您为 Spotify
any
打字没有任何属性。 ;) Best bet would check if Spotify has a type library and use it here. ;) 最好的办法是检查 Spotify 是否有类型库并在此处使用它。 Otherwise you can use a type with the properties you pointing to.
否则,您可以使用具有您指向的属性的类型。
type SpotifyType {
properties: any; // better to look for the typing config
}
var Spotify:SpotifyType
Another option is to try !
另一种选择是尝试
!
Nonnull assertion非空断言
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.