javascript - React 中如何添加 setTimeout?
大家讲道理
大家讲道理 2017-04-11 12:51:21
[JavaScript讨论组]

项目是用react写的,然后现在有个需求,就是三秒后跳转到一个新的页面,对于原生来说,就是一个setTimeout搞定的问题,但是在react中,这个要怎么弄?如何添加上去?是关于生命周期吗,在生命周期的某个阶段加载定时器吗?看到native里面有定时器,但我这里只用react,貌似没用到它,应该调不了吧,各种懵逼,求大神带飞。
需求:3秒后跳转到新的页面

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
PHPz

谢谢邀请!写法很简单,就是在componentDidMount设置setTimeout,然后在componentWillUnmount取消,防止内存泄漏。下面是一般的写法:

首先如果不是es6 class的写法,你可以用如下TimerMixin的写法,当然手动清除也是可以的,不过用的多的话Mixin个人觉得好点:

var TimerMixin = require('react-timer-mixin');

var Component = React.createClass({
  mixins: [TimerMixin],
  componentDidMount: function() {
    this.setTimeout(
      () => { console.log('这样我就不会导致内存泄露!'); },
      500
    );
  }
});

针对es6 class 不能用mixin,我暂时这样写的:

export default class Hello extends Component {
  componentDidMount() {
    this.timer = setTimeout(
      () => { console.log('把一个定时器的引用挂在this上'); },
      500
    );
  }
  componentWillUnmount() {
    // 如果存在this.timer,则使用clearTimeout清空。
    // 如果你使用多个timer,那么用多个变量,或者用个数组来保存引用,然后逐个clear
    this.timer && clearTimeout(this.timer);
  }
};
伊谢尔伦
class MyComp extends Component {
  componentDidMount() {
    this.timeoutId = setTimeout(() => {
      window.location.href = "/foo/bar"
    }, 3000)
  }

  componentWillUnmount() {
    clearTimeout(this.timeoutId)
  }

  render() {
    // Blah blah
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号