谢谢邀请!写法很简单,就是在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);
}
};