将 JS 函数添加到 ReactJS - Spotify Web Playback SDK

Adding a JS function to ReactJS - Spotify Web Playback SDK


我正在尝试使用 ReactJS 前端在 Node.js 中实现 Spotify Web Playback SDK。 Spotify 开发人员指南提供了以下代码(缩写为重要部分)以在 HTML:

中实现 SDK

<script src="https://sdk.scdn.co/spotify-player.js"></script>
<script>
      window.onSpotifyWebPlaybackSDKReady = () => {
          const token = '[My Spotify Web API access token]';
          const player = new Spotify.Player({
              name: 'Web Playback SDK Quick Start Player',
              getOAuthToken: cb => { cb(token); }
          });
          // Connect to the player!
          player.connect();
      };
</script>

我已经设法通过使用 react-load-script 获取了外部脚本 运行,但是我不知道如何添加 SDK 准备就绪时调用的 window.onSpotifyWebPlaybackSDKReady 回调。
有人可以建议如何最好地实施吗?

解决方案:感谢 Piotr Szlagura 的回答。我发现有效的代码如下所示。

import React, { Component } from 'react';
import Script from 'react-load-script';
import './App.css';


class App extends Component {

  constructor(props) {
    super(props);
    this.handleLoadSuccess = this.handleLoadSuccess.bind(this);
    this.handleLoadFailure = this.handleLoadSuccess.bind(this);
    this.cb = this.cb.bind(this);
  }

  componentDidMount() {
    window.onSpotifyWebPlaybackSDKReady = () => {
      this.handleLoadSuccess();
    };
  }

  handleLoadSuccess() {
    this.setState({ scriptLoaded: true });
    console.log("Script loaded");
    const token = '[My Spotify Web API access token]';
    const player = new window.Spotify.Player({
      name: 'Web Playback SDK Quick Start Player',
      getOAuthToken: cb => { cb(token); }
    });
    console.log(player);

    // Error handling
    player.addListener('initialization_error', ({ message }) => { console.error(message); });
    player.addListener('authentication_error', ({ message }) => { console.error(message); });
    player.addListener('account_error', ({ message }) => { console.error(message); });
    player.addListener('playback_error', ({ message }) => { console.error(message); });

    // Playback status updates
    player.addListener('player_state_changed', state => { console.log(state); });

    // Ready
    player.addListener('ready', ({ device_id }) => {
      console.log('Ready with Device ID', device_id);
    });

    // Not Ready
    player.addListener('not_ready', ({ device_id }) => {
      console.log('Device ID has gone offline', device_id);
    });

    // Connect to the player!
    player.connect();
  }

  cb(token) {
    return(token);
  }

  handleScriptCreate() {
    this.setState({ scriptLoaded: false });
    console.log("Script created");
  }

  handleScriptError() {
    this.setState({ scriptError: true });
    console.log("Script error");
  }

  handleScriptLoad() {
    this.setState({ scriptLoaded: true});
    console.log("Script loaded");
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <Script
            url="https://sdk.scdn.co/spotify-player.js"
            onCreate={this.handleScriptCreate.bind(this)}
            onError={this.handleScriptError.bind(this)}
            onLoad={this.handleScriptLoad.bind(this)}
          />
        </header>
      </div>
    );
  }
}
export default App;

综上所述,在渲染函数中添加Spotify Web Playback SDK作为脚本标签,然后在componentDidLoad中连接onSpotifyWebPlaybackSDKReady回调,这样我们就知道需要的部分会有rendered/loaded.

我建议 运行 在您的组件的 componentDidMount 方法中使用此代码。如果您使用服务器端渲染,您还应该检查 window 是否存在(componentDidMount 不应在服务器端触发,但这样更安全)。

基本上根据我的经验,我发现 window 上的每个操作(如添加事件侦听器等)如果在 componentDidMount 中被触发,则工作正常。

记得在 componentWillUnmount 中删除此侦听器以防止内存泄漏。