我正在学习本机的反应,并且以下的Mixins用于在Umount
之后清除计时器,但我对以下代码感到困惑:
From Reusable Component
var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.forEach(clearInterval);
}
};
var TickTock = React.createClass({
mixins: [SetIntervalMixin], // Use the mixin
getInitialState: function() {
return {seconds: 0};
},
componentDidMount: function() {
this.setInterval(this.tick, 1000); // Call a method on the mixin
},
tick: function() {
this.setState({seconds: this.state.seconds + 1});
},
render: function() {
return (
<p>
React has been running for {this.state.seconds} seconds.
</p>
);
}
});
ReactDOM.render(
<TickTock />,
document.getElementById('example')
);
问题: 这意味着什么:
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
当我尝试使用setTimeout
:
componentDidMount: function() {
setTimeout(() => this.setState({seconds: this.state.seconds + 0.5}), 500); // Call a method on the mixin
},
但计时器无效。