momentjs - fromNow()方法在通用(同构)js应用程序
momentjs - fromNow() method in universal (isomorphic) js app
我有一个用node.js和react.js构建的应用程序,它是通用的(或以前称为"同构的"),并与REST API交谈以获取数据。
在某些组件的render
方法中,我以2 days ago
或few 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;
}
}
相关文章:
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- Emberjs应用程序加载在除Index之外的所有路由上
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- angular 1.5应用程序中的导航栏
- 在同构应用程序中使用redux
- 如何在同构应用程序中通过节点提取传递请求cookie
- 同构JS应用程序中的环境变量:Webpackfind&代替
- 在同构的React web应用程序中,选择服务器渲染的最佳方式是什么
- 如何使用 Restify 在同一端口上运行多节点应用程序
- ReactJS 同构应用程序和系统服务器时间
- 在同构 Redux 应用程序中设置 cookie 的位置
- 异构(JavaEE+JavaScript)应用程序构建
- 在同构应用程序上运行mocha测试时,无法导入SCSS文件
- 什么'是构建通用/同构React/Redux web应用程序的过程
- momentjs - fromNow()方法在通用(同构)js应用程序
- 错误建立在Heroku -同构应用程序
- 在渲染客户端(同构)之前应用css
- 从同构应用程序访问导航器对象的优雅解决方案