我有一些带有日期时间字段的数据,我想使用 momentJS fromNow()
显示相对日期时间。然而,在初始加载后,它显示时间戳为几秒钟前
。但在触发下一个状态更改之前,此信息不会更新。 通过 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 秒后,您应该会看到文本从“几秒钟前”更改为“一分钟前”。
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')
);
关于reactjs - redux Reactjs 中的相对时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35983705/