首页 > 解决方案 > 如何根据 API 的新响应更新状态?

问题描述

我正在尝试使用 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>

我希望能够不断检查是否发送了新的响应,但它不会自动更新。

标签: reactjs

解决方案


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

这个伪代码/示例没有使用 Spotify API,但逻辑应该类似。

CodePen 镜子

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>


推荐阅读