我正在使用reactjs进行我的项目,我希望不久前在table.i使用时刻js来显示时间(fromNow())但它只显示数据来自server.And时的几秒钟如果数据不是来自服务器,它会在6小时前直接显示。比较6小时前显示的时间间隔为2分钟。如下表所示。
我的项目代码如下所示
componentDidMount() {
let socket = new WebSocket('wss://api.example.com.np/ws');
this.setState({ socket: socket,noOfVehicle:this.state.supportInfo.length });
this.getSupportInfo();
socket.onmessage = ((message) => {
let socketData = JSON.parse(message.data);
let device_id = socketData[0].device_id;
let updatedSupportInfo = this.getUpdatedInfo(this.state.sourceName);
let flag = true;
let uSupport = updatedSupportInfo.map(function(item){
if(device_id == item.device_id){
item.current_pos = socketData[0].current_pos;
if(item.current_pos){
flag = true;
item["latlng"] = item.current_pos.x + ',' + item.current_pos.y;
}else{
flag = false;
}
let time = new Date(socketData[0].timestamp);
let now = new Date();
let timeAgoIn = moment(time).fromNow(true);
item["timeAgoIn"] = timeAgoIn;
}
getSupportInfo() {
axios({
method: 'get',
url: 'https://support.taranga.com.np/support_info'
})
.then((response) => {
for (var i = 0; i < response.data.length; i++) {
if(response.data[i].current_pos){
response.data[i]["latlng"] = response.data[i].current_pos.x + ',' + response.data[i].current_pos.y;
let time = new Date(response.data[i].timestamp)
let now = new Date();
let a = moment(time);
let b = moment(now);
let timeAgo = b.diff(a, 'hours')
let timeAgoIn = moment(time).fromNow(true)
response.data[i]["timeAgo"] = timeAgo;
response.data[i]["timeAgoIn"] = timeAgoIn;
}
}
this.setState({
supportInfo: response.data
});
})
.catch((error)=>{
throw (error);
});
}
getUpdatedInfo(name) {
let uInfo = [];
let tempSupport = this.state.supportInfo.slice();
_.map(tempSupport,(value,key) =>{
if(value.timeAgo !=0){
let time = new Date(value.timestamp)
let now = new Date();
let a = moment(time);
let b = moment(now);
let timeAgo = b.diff(a, 'minutes')
console.log(timeAgo);
//let timeAgo = moment.duration(b-a).humanize()
let timeAgoIn = moment(time).fromNow(true)
value["timeAgo"] = timeAgo;
value["timeAgoIn"] = timeAgoIn;
}
});
this.setState({
supportInfo:tempSupport
});
表中显示的代码是
<TableHeaderColumn dataField="timeAgoIn" dataSort={true}>Time Ago</TableHeaderColumn>
答案 0 :(得分:0)
我相信你的逻辑是有缺陷的,当你得到你存储timeAgo的信息一次,但timeAgo是一个随时间变化的属性,例如:
您在12:00收到消息,您将timeAgo设置为1秒(或者将其设置为w / e js) 你在12点05分检查你的屏幕,timeAgo对于那条消息仍然是1秒,因为这是计算一次,但是时间已经过去了,timeAgo应该是5秒前,对吗?
timeAgo属性应保留为您从服务器收到的时间戳,并在刷新表时计算(当您想要执行此操作时是另一个主题)