栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

React应用中的setInterval

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

React应用中的setInterval

我发现您的代码有4个问题:

  • 在计时器方法中,您始终将当前计数设置为10
  • 您尝试在render方法中更新状态
  • 您没有使用
    setState
    方法来实际更改状态
  • 您没有在状态中存储intervalId

让我们尝试解决该问题:

componentDidMount: function() {   var intervalId = setInterval(this.timer, 1000);   // store intervalId in the state so it can be accessed later:   this.setState({intervalId: intervalId});},componentWillUnmount: function() {   // use intervalId from the state to clear the interval   clearInterval(this.state.intervalId);},timer: function() {   // setState method is used to update the state   this.setState({ currentCount: this.state.currentCount -1 });},render: function() {    // You do not need to decrease the value here    return (      <section>       {this.state.currentCount}      </section>    );}

这将导致计时器从10减少到-N。如果您希望计时器减少到0,则可以使用稍微修改的版本:

timer: function() {   var newCount = this.state.currentCount - 1;   if(newCount >= 0) {        this.setState({ currentCount: newCount });   } else {       clearInterval(this.state.intervalId);   }},


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616461.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号