簡體   English   中英

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

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

我有一個使用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端而不是在應用程序端格式化日期? 你的想法?

謝謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM