为了账号安全,请及时绑定邮箱和手机立即绑定

React:如何强制一个函数在另一个函数完全完成后运行?

React:如何强制一个函数在另一个函数完全完成后运行?

catspeake 2023-03-24 16:22:38
在这个 React Pomodoro Clock 中,有一个函数countDown。其中有一个函数叫做three. 当前,this.setState({ init: 'break' }); 在 中设置时two,three立即发生。但是,three应该等到two完成。任何帮助将不胜感激。
查看完整描述

3 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

您需要使它们异步。


喜欢...


const one = async () => {

  //some code

return

}

const two = async () => {

  //some code

return

}

const three = async () => {

  //some code

return

}

然后你可以...


one().then(two).then(three)


查看完整回答
反对 回复 2023-03-24
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

解决方案:


使用数组来保存状态和持续时间:


const states = [ { name: 'session', duration: 1500 }, { name: 'break', duration: 300 } ]

交替数组的索引以在会话和中断之间交替。


countDown(id){

    // set the function to a variable and set state to it, so the function

    // can be paused with clearInterval()

    var intervalFunc = setInterval(() => down(this.state.timeLeftSeconds--), 1000);

    this.setState({intervalFunc: intervalFunc});


    const down = (time) =>

    {


      if(time > 0){

        // converts seconds to MM:SS at every t-minus

        this.setState({ timeLeft: secondsToMins(time)});

        console.log(time);

        console.log(this.state.timeLeft);

      }


      if (time <= 0) {

        this.setState({ timeLeft: secondsToMins(time)});

        let sound = document.getElementById(id).childNodes[0];

        sound.play();


        let stateIndex = (this.state.stateIndex + 1) % states.length;

        this.setState({ stateIndex: stateIndex});

        this.setState({ timeLeftSeconds: states[stateIndex].duration});

        this.setState({ init: states[stateIndex].name});

        console.log(this.state.init);

      }

    }

  }


查看完整回答
反对 回复 2023-03-24
?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

您可以通过使函数返回 aPromise并使用async / await关键字等到它们完成后再开始下一个来做到这一点。


const setDelay = delay => new Promise(resolve => {

  console.log(`Process running for ${delay}`);

  setTimeout(() => {

    console.log('Process done');

    resolve();

  }, delay);

});


(async () => {

  

  await setDelay(2000);

  await setDelay(3000);

  await setDelay(1000);

  

})();


或者你可以不用async / await并链接承诺。


const setDelay = delay => new Promise(resolve => {

  console.log(`Process running for ${delay}`);

  setTimeout(() => {

    console.log('Process done');

    resolve();

  }, delay);

});


setDelay(3000)

  .then(() => setDelay(1000))

  .then(() => setDelay(4000));


或者只是使用良好的老式回调。但我会选择上述之一。


查看完整回答
反对 回复 2023-03-24
  • 3 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信