【问题标题】:momentjs - fromNow() method in universal (isomorphic) js appmomentjs - 通用(同构)js 应用程序中的 fromNow() 方法
【发布时间】:2016-01-07 12:38:56
【问题描述】:

我有一个使用 node.js 和 react.js 构建的应用程序,它是通用的(或之前称为“同构的”),并与 REST API 对话以获取数据。

在某些组件的render 方法中,我以2 days agofew seconds ago 等格式显示日期,在这种情况下,moment.js 可以完美运行。我说的是它的'方法fromNow(),例如:

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

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

但问题就在这里:

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>

我假设服务器时间和客户端时间可能不同,这会导致问题。在这种情况下,最好的解决方案是什么?也许值得在 API 端而不是在应用程序端格式化日期?你的想法?

谢谢!

【问题讨论】:

  • 您找到解决问题的方法了吗?

标签: javascript node.js reactjs momentjs universal


【解决方案1】:

我对 MomentJs 也有同样的问题。我选择了一个小的 Javascript 助手,我的同构组件一切都很好......

1.组件

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

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;
      }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    相关资源
    最近更新 更多