如何根据API的新响应更新状态?

时间:2019-08-01 00:22:23

标签: reactjs

我正在尝试使用Spotify的API更新当前播放的曲目。 目前,我正在提取正确的歌曲,但是当我更改曲目时,仍会显示当前歌曲。

有什么办法让我的状态等待新的响应,然后更新,而不必每秒运行一次setInterval?

我尝试使用setInterval起作用,但是需要我的状态每秒运行一次以检测更改,而不仅仅是等待API的响应更改。

这是我要从Spotify API中提取的状态:

getNowPlaying() {
    setInterval(() => {
      spotifyApi.getMyCurrentPlaybackState().then(response => {
        this.setState({
          nowPlaying: {
            name: response.item.name,
            image: response.item.album.images[0].url,
            artists_name: response.item.artists[0].name,
            artists_id: response.item.artists[0].id
          }
        });
      });
    }, 1000);
  }

我在这里显示它:

<div className="current-user">
     <img
      alt="currentuser"
      className="rounded-image"
      src={this.state.currentInfo.display_image}
      style={{ height: 150 }}
      />
      <div>{this.state.currentInfo.display_name}</div>
   </div>

我希望能够不断检查是否发送了新回复,但不会自动更新。

1 个答案:

答案 0 :(得分:0)

在收到API响应后,您应该点击“下一步”按钮,并更新状态。当用户单击下一步时,我假设您正在向Spotify发送API请求以获取下一首歌曲,此时您应该更新状态。

此伪代码/示例未使用Spotify API,但逻辑应相似。

CodePen Mirror

class ApiFetcher extends React.Component {
  state = {
    apiData: "",
    track: 1
  };

  componentDidMount() {
    this.getNextFromApi();
  }

  getNextFromApi = () => {
    fetch(`https://jsonplaceholder.typicode.com/todos/${this.state.track}`)
      .then(response => response.json())
      .then(json => {
        this.setState({
          track: this.state.track + 1,
          apiData: json
        });
      });
  }

  render() {
    return (
      <div>
        <button onClick={this.getNextFromApi}>Next Track</button>
        {this.state.apiData ? (
          <pre>{JSON.stringify(this.state.apiData, null, 2)}</pre>
        ) : (
          <p>Unable to get next track..</p>
        )}
      </div>
    );
  }
}

class App extends React.Component {
  render() {
    return <ApiFetcher />;
  }
}

ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>