首页 > 解决方案 > 如何通过 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);
        });

标签: reactjsspotify

解决方案


如果您一个接一个地调用函数,您可以尝试 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);
      });

推荐阅读