javascript - React 中如何添加 setTimeout?
本文介绍了javascript - React 中如何添加 setTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
项目是用react写的,然后现在有个需求,就是三秒后跳转到一个新的页面,对于原生来说,就是一个setTimeout搞定的问题,但是在react中,这个要怎么弄?如何添加上去?是关于生命周期吗,在生命周期的某个阶段加载定时器吗?看到native里面有定时器,但我这里只用react,貌似没用到它,应该调不了吧,各种懵逼,求大神带飞。
需求:3秒后跳转到新的页面
解决方案
谢谢邀请!写法很简单,就是在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);
}
};
这篇关于javascript - React 中如何添加 setTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文