I'm writing a timer to auto-update the posted time. The code works well without this._timer, and the app crushed with "TypeError: Cannot read property 'comment' of undefined"
when I set the timer up.
I tried this._timer = setInterval(this._updateTimeString.bind(this), 3000);
instead of this._timer = setInterval(this._updateTimeString, 3000);
, it works but I don't know why.
componentWillMount() {
this._updateTimeString();
this._timer = setInterval(this._updateTimeString, 3000);
}
_updateTimeString() {
const now = Date.now();
const duration = (now - this.props.comment.createdTime) / 1000;
const timeDuration =
duration > 60
? duration >= 60 * 2
? duration > 60 * 60
? duration >= 60 * 60 * 2
? duration > 60 * 60 * 24
? duration > 60 * 60 * 24 * 2
? `${Math.round(duration / (60 * 60 * 24))} days ago`
: `${Math.round(duration / (60 * 60 * 24))} day ago`
: `${Math.round(duration / (60 * 60))} hours ago`
: `${Math.round(duration / (60 * 60))} hour ago`
: `${Math.round(duration / 60)} mins ago`
: `${Math.round(duration / 60)} min ago`
: `${Math.round(Math.max(duration, 1))} s ago`;
this.setState({
timeString: timeDuration
});
}