【问题标题】:Adding a JS function to ReactJS - Spotify Web Playback SDK向 ReactJS 添加 JS 函数 - Spotify Web Playback SDK
【发布时间】:2019-06-25 10:54:32
【问题描述】:


我正在尝试使用 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 回调,以便我们知道所需的部分将已渲染/加载。

【问题讨论】:

  • 感谢您提供现成的解决方案。这正是我在使用 Spotify 学习 React 时所寻找的。​​span>

标签: javascript node.js reactjs spotify


【解决方案1】:

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

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

记得删除componentWillUnmount中的这个监听器以防止内存泄漏。

【讨论】:

    猜你喜欢
    • 2018-07-19
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多