reactjs - 如何通过 SetState 使用/制作回调函数
问题描述
constructor(props) {
super(props);
this.state=({
year: (props.location.state && props.location.state.year) || '',
real_id: ''
});
我在这里将“real_id”状态变量设置为播放列表 id,当我在控制台记录它时,它会正确返回 id。但是当我将曲目添加到播放列表时,'real_id' 是未定义的。我理解这是因为 setState 是一个异步函数,但我不确定如何通过传递“real_id”变量为此创建一个“回调”函数,因为这是我第一次使用 React。
spotifyApi.createPlaylist(this.state.users, { 'name' : "Phaseify " + this.state.year, 'public' : true })
.then((response) => {
this.setState({
real_id: response.id
});
console.log('Created playlist!');
}, function(err) {
console.log('Something went wrong!', err);
});
spotifyApi.addTracksToPlaylist({"playlistId": this.state.real_id, "tracks": top_track_ids})
.then((response) => {
console.log("CREATED");
}, function(err){
console.log("An error", err);
});
解决方案
如果您一个接一个地调用函数,您可以尝试
setState
接受一个回调函数,该函数在状态更新时被调用,您可以addTracksToPlaylist
在回调中调用函数
spotifyApi.createPlaylist(this.state.users, { 'name' : "Phaseify " + this.state.year, 'public' : true })
.then((response) => {
this.setState({
real_id: response.id
},function(){
// callback function which gets called when state is set with real_id
spotifyApi.addTracksToPlaylist({"playlistId":
this.state.real_id, "tracks": top_track_ids})
.then((response) => {
console.log("CREATED");
}, function(err){
console.log("An error", err);
});
});
console.log('Created playlist!');
}, function(err) {
console.log('Something went wrong!', err);
});
推荐阅读
- debugging - Keras 自定义损失:想要在每个 epoch 结束时跟踪每个损失值
- javascript - 我们可以将柏树与 Jenkins 构建工作集成吗
- c# - 如何在 c# asp.net web 表单中计算财政年度
- node.js - 弹性转储安装问题。失败的依赖
- javascript - 导航栏在 bootstrap 和 jQuery 中不起作用
- python - 在 Tensorflow 运行时更改 tf.dataset 源
- c# - Entity Framework 6 不创建映射表
- jquery - Ajax Post 请求在部署 Asp.NET MVC 上不起作用
- actions-on-google - google actions sdk:获取请求 webhook 的项目 id
- microsoft-graph-api - Microsoft Graph API for Education:错误列出用户学校