DateTime: avoid unnecessary update #6110
1 changed files with 49 additions and 3 deletions
|
@ -2,15 +2,29 @@
|
|||
import React from 'react';
|
||||
import moment from 'moment';
|
||||
|
||||
const DEFAULT_MIN_UPDATE_DELTA_MS = 60 * 1000;
|
||||
|
||||
type Props = {
|
||||
date?: any,
|
||||
timeAgo?: boolean,
|
||||
formatOptions: {},
|
||||
formatOptions?: {},
|
||||
show?: string,
|
||||
clock24h: boolean,
|
||||
clock24h?: boolean,
|
||||
minUpdateDeltaMs?: number,
|
||||
};
|
||||
|
||||
class DateTime extends React.PureComponent<Props> {
|
||||
type State = {
|
||||
lastRenderTime: Date,
|
||||
};
|
||||
|
||||
class DateTime extends React.Component<Props, State> {
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
lastRenderTime: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
static SHOW_DATE = 'date';
|
||||
static SHOW_TIME = 'time';
|
||||
|
||||
|
@ -45,6 +59,38 @@ class DateTime extends React.PureComponent<Props> {
|
|||
return __(strId, { duration });
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props): boolean {
|
||||
if (
|
||||
moment(this.props.date).diff(moment(nextProps.date)) !== 0 ||
|
||||
this.props.clock24h !== nextProps.clock24h ||
|
||||
this.props.timeAgo !== nextProps.timeAgo ||
|
||||
this.props.minUpdateDeltaMs !== nextProps.minUpdateDeltaMs ||
|
||||
this.props.show !== nextProps.show
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.props.timeAgo && nextProps.timeAgo) {
|
||||
const minUpdateDeltaMs = this.props.minUpdateDeltaMs || DEFAULT_MIN_UPDATE_DELTA_MS;
|
||||
const prev = moment(this.state.lastRenderTime);
|
||||
const curr = moment(new Date());
|
||||
const deltaMs = curr.diff(prev);
|
||||
|
||||
if (deltaMs > minUpdateDeltaMs) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
componentDidUpdate() {
|
||||
const { timeAgo } = this.props;
|
||||
if (timeAgo) {
|
||||
this.setState({ lastRenderTime: new Date() });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { date, timeAgo, show, clock24h } = this.props;
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue