繁体   English   中英

类型错误:在使用 spotify 的 api 时无法读取未定义的属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM