我试图将Spotify的脚本链接到我的组件,但是当我使用“ useEffect”进行操作时,窗口无法识别“ onSpotifyWebPlaybackSDKReady”属性。错误是:“ Window类型的属性不存在onSpotifyWebPlaybackSDKReady属性&typeOf globalThis'“。我如何解决?
import React, { useEffect } from 'react';
function SpotifyPlayer() {
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.onSpotifyWebPlaybackSDKReady = () => {
// You can now initialize Spotify.Player and use the SDK
};
}
export default SpotifyPlayer;
它在文件夹中的组件,公共html在另一个文件夹中。
答案 0 :(得分:0)
编辑:我刚刚看到这个window.onSpotifyWebPlaybackSDKReady
是您绑定到窗口上的函数,以便在加载Spotify脚本时执行。
更容易。您只需要确保您也可以在useEffect挂钩中调用此方法:
import React, { useEffect } from 'react';
function SpotifyPlayer() {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
const script = document.createElement("script");
script.src = "https://sdk.scdn.co/spotify-player.js";
script.async = true;
document.body.appendChild(script);
window.onSpotifyWebPlaybackSDKReady = () => {
// do your spotify magic here.
}
}, []);
}
export default SpotifyPlayer;