简体   繁体   English

服务器和客户端中的Node Js和React js SSR时间不匹配

[英]Node Js and React js SSR time in server and client is not matched

I am dealing with Node js and React js Server Side Rendering. 我正在处理Node js和React js服务器端渲染。 I have encountered a problem. 我遇到了一个问题。 I save time under ISO format on MongoDB, so I need to convert it to regular format, and the result of the conversion is different between server and client due to the difference of server's timezone and client's timezone (I need MM/dd/YYYY HH:mm format). 我在MongoDB上以ISO格式节省了时间,因此我需要将其转换为常规格式,并且由于服务器的时区和客户端的时区的不同,服务器和客户端之间的转换结果有所不同(我需要MM / dd / YYYY HH :mm格式)。 Of course, react throws a warning about it. 当然,react会对此发出警告。 I used moment.js and toLocalString(). 我使用了moment.js和toLocalString()。 Do you guys have any possible solutions to resolve this problem? 你们有任何可能的解决方案来解决此问题吗?

Thank you guys so much. 谢谢你们

As you said, the problem is due to the difference between the server's timezone and the client's timezone. 如您所说,问题是由于服务器的时区和客户端的时区之间的差异引起的。 One way to fix this is to render the ISO timestamp on the server and later replace it with local time on the client-side in componentDidMount() . 解决此问题的一种方法是在服务器上呈现ISO时间戳,然后在componentDidMount()中将其替换为客户端的本地时间。

React docs say that componentWillMount() is the only lifecycle method called on server rendering so it's safe to write timezone related logic in componentDidMount() . React docs表示 componentWillMount()是服务器渲染上调用的唯一生命周期方法,因此可以在componentDidMount()编写与时区相关的逻辑是安全的。

document.querySelectorAll('...').forEach(el => {
  const timestamp = Number(el.textContent)
  const timezoneOffset = new Date().getTimezoneOffset() * 60 * 1000 // milliseconds
  const localDate = new Date(timestamp - timezoneOffset)
  el.textContent = formattedDate(localDate, 'my-custom-format') // use custom formatting here
})

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

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