简体   繁体   English

moment.js-通用(同构)js应用程序中的fromNow()方法

[英]momentjs - fromNow() method in universal (isomorphic) js app

I have an application which is built with node.js and react.js and is universal (or "isomorphic" as they were called before) and speaks with REST API to get data. 我有一个使用node.js和react.js构建的应用程序,该应用程序是通用的(或以前称为“同构”),并且使用REST API进行获取数据。

In render method of some component I'm displaying date in format like 2 days ago or few seconds ago and with this case moment.js works perfectly. 在某些组件的render方法中,我以2 days agofew seconds ago格式显示日期,在这种情况下,moment.js可以完美地工作。 I'm talking about its' method fromNow() , for example: 我说的是fromNow()的方法,例如:

render() {
  const { date } = this.props;
  const formattedDate = moment(date).fromNow();

  return (
    <div>{formattedDate}</div>
  );
}

But here is the problem: 但这是问题所在:

Warning: React attempted to reuse markup in a container but the
checksum was invalid. This generally means that you are using server
rendering and the markup generated on the server was not what the
client was expecting. React injected new markup to compensate which
works but you have lost many of the benefits of server rendering.
Instead, figure out why the markup being generated is different on the
client or server:
(client) 0:0.2.1.0.1.0.3.2">14 minutes ago</div>
(server) 0:0.2.1.0.1.0.3.2">17 minutes ago</div>

I assume that server time and client time might be different and that causes the problem. 我认为服务器时间和客户端时间可能不同,这会导致问题。 What will be the best solution in this case? 在这种情况下最好的解决方案是什么? Maybe it's worth to format date on API side and not on the application's? 也许值得在API端而不是在应用程序端格式化日期? Your ideas? 你的想法?

Thanks! 谢谢!

I had the same problem with MomentJs. 我在MomentJs上也遇到了同样的问题。 I opted for a small Javascript helper and everything was fine with my isomorphic component ... 我选择了一个小型Javascript助手,并且同构组件一切都很好...

1. Component 1.组成部分

  _fetch() {
    return this.props.store.dispatch(loadActs()).then(
      results => {
        const inclSeconds = true;
        this.setState({
          ...... 
          lastUpdate: formatAMPM(new Date(), inclSeconds).toString()
        })
      }
    )
  }

2. helper utility 2.助手实用程序

module.exports = {
    formatAMPM: (date, inclSecs=false) => {
        let hours = date.getHours();
        let minutes = date.getMinutes();
        let seconds = date.getSeconds();
        let ampm = hours >= 12 ? 'PM' : 'AM';
        let strTime= ''
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+ minutes : minutes;
        seconds = seconds < 10 ? '0'+ seconds : seconds;
        if (inclSecs) {
          strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
        } else {
          strTime = hours + ':' + minutes + ' ' + ampm;
        }
        return strTime;
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM