redux reactjs 中的相对时间

relative time in redux reactjs

我有一些带有日期时间字段的数据,我想使用 momentJS fromNow() 显示相对日期时间。然而,在初始加载后,它显示时间戳为 a few seconds ago。但这不会更新,直到触发下一个状态更改。 在状态树中保持另一个状态并通过 componentDidUpdate 中的定时器函数 setInterval 进行控制是一个好习惯吗?

render()
{
   // get the new prop value here which triggered from a setInterval -> action -> reducer -> state change -> propagate to connected components
   const text = comment.get('text');
   const dateTime = moment(comment.get('dateTime')).fromNow();
   return (
     // add the new prop into the component
     <div key={id}>
        <Comment
         text = {text}
         dateTime = {dateTime}
     </div>
}

我草草记下了一个组件,该组件采用纪元时间戳并为其显示 momentjs 文本。 文本每 300 毫秒通过内部组件状态更新一次,您可以根据需要进行更改。

您可以在 this fiddle 上注意到,每个新文本都会记录在控制台中。 45 秒后,您应该会看到文本从 "a few seconds ago" 变为 "a minute ago"。

Fiddle here,这是代码:

var MomentTime = React.createClass({
  getInitialState: function() {
    return {text: ""};
  },

  componentWillMount: function() {
    this._updateMomentText();
    this.interval = setInterval(this._updateMomentText, 300);
  },

  componentWillUnmount: function() {
    clearInterval(this.interval);
  },

  _updateMomentText: function() {
    var text = moment(this.props.timestamp).fromNow()
    console.log(text)
    if(text !== this.state.text) {
        this.setState({text: text});
    }
  },

  render: function() {
    return <div>{this.state.text}</div>;
  }
});

ReactDOM.render(
  <MomentTime timestamp={new Date().getTime()} />,
  document.getElementById('container')
);