reactjs - 如何根据 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>
我希望能够不断检查是否发送了新的响应,但它不会自动更新。
解决方案
在收到 API 响应后,您应该点击“Next Track”按钮并更新您的状态。当用户单击下一步时,我假设您正在向 Spotify 发送 API 请求以获取下一首歌曲,此时您应该更新您的状态。
这个伪代码/示例没有使用 Spotify API,但逻辑应该类似。
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>
推荐阅读
- excel - 在自定义函数中使用 findnext 不起作用
- python - Keras 中的自定义层
- docker - Elastalert 多次查询(点击)计数值
- django - django 在 paginate_queryset 中设置自定义页码
- list - Prolog:P-12:九十九个 Prolog 问题(修改)
- python - 从列表创建任务 - Airflow
- selenium - 当我使用scrapy而不是当我使用selenium并请求403错误代码时我被阻止了
- python - 我找不到如何提供从 html 按钮下载具有 azure 媒体服务的视频
- elastic-stack - filebeat pod 多次重启,但没有在 kibana 中获取日志
- vb.net - 如何使用 odbc 连接到 as400 for vb.net