如何使用 SetState Use/Make 回调函数
How to Use/Make Callback Function with 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' 变量为此创建一个 'callback' 函数,因为这是我第一次使用 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);
});
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' 变量为此创建一个 'callback' 函数,因为这是我第一次使用 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);
});