如何实时自动刷新数据,做出反应?

时间:2020-03-03 21:24:45

标签: javascript node.js reactjs api spotify

首次使用React制作基本的Spotify应用。当前,“正在播放”功能正在使用按钮来显示用户正在播放的内容。如何更改此命令,使其与单击按钮相对应地实时执行?

<button onClick={() => this.getNowPlaying()}>
   Check Now Playing
 </button>

任何帮助都会很棒:) 完整的代码示例如下

import React, { Component } from 'react';
import './App.css';
import Spotify from 'spotify-web-api-js';

const spotifyWebApi = new Spotify();

class App extends Component {
  constructor(){
    super();
    const params = this.getHashParams();
    this.state ={
      loggedIn: params.access_token ? true : false,
      nowPlaying: {
        name: 'Not Checked',
        image: ''
       }
     }
    if (params.access_token){
      spotifyWebApi.setAccessToken(params.access_token)
    }
  }
  getHashParams() {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = window.location.hash.substring(1);
    while ( e = r.exec(q)) {
       hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
  }

  getNowPlaying(){
    spotifyWebApi.getMyCurrentPlaybackState()
      .then((response) => {
        this.setState({
          nowPlaying: {
            name: response.item.name,
            image: response.item.album.images[1].url
          }
        })
      }
    )
  }

  render() {
    return (
    <div className="App">
      <a href='http://localhost:8888'>
      <button>Login But With Spotify </button>
      </a>
      <div> Now Playing: { this.state.nowPlaying.name} </div>
    <div>
    <img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
    </div>
    <button onClick={() => this.getNowPlaying()}>
      Check Now Playing
    </button>
    </div>

2 个答案:

答案 0 :(得分:1)

不确定“实时”到底是什么意思,但是您可以设置一个时间间隔以使用api检查正在播放的歌曲。

类似的东西:

class App extends Component {
//your code ..

this.interval;

componentDidMount() {
  this.interval = setInterval(this.getNowPlaying, 500); // <- time in ms
}

stopInterval() {
  clearInterval(this.interval);
}

componentWillUnmount() {
  this.stopInterval();
}
}

答案 1 :(得分:0)

您可以添加

export default function ModalProduct(props) {
  return (
    <Modal show={props.showModal} onHide={props.handleClose}>
      ...
    </Modal>
  );
}

我个人并不喜欢这种方法。但这是一个开始。