简体   繁体   中英

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.

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. I'm talking about its' method fromNow() , for example:

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? Your ideas?

Thanks!

I had the same problem with MomentJs. I opted for a small Javascript helper and everything was fine with my isomorphic component ...

1. Component

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

2. helper utility

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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