我正在尋找一種方法來優化我的代碼。如何避免在我的情況下使用2個狀態變量?
有沒有辦法只使用1個狀態變量(開始)而不是2個(開始和現在)?
這是我的代碼(一個非常簡單的定時器):
var Timer = React.createClass({
getInitialState: function() {
return {
started: new Date().getTime(),
now: 0
}
},
render: function() {
return (
<div>
<strong>{this.state.now}</strong>
<button type="button" onClick={this.resetCounter}>Reset</button>
</div>
);
},
componentDidMount: function() {
this.tickInterval = setInterval(this.doTick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.tickInterval);
},
doTick: function() {
let newDate = new Date().getTime();
let newCounter = Math.round((newDate - this.state.started)/1000);
this.setState({ now: newCounter });
},
resetCounter: function() {
this.setState({ started: new Date().getTime(), now: 0 });
},
});
ReactDOM.render(<Timer />, document.getElementById('root'));