[英]How should date strings be handled when rendering on both server and client?
I am creating a blog using NextJS and luxon .我正在使用 NextJS 和luxon创建一个博客。
The server does not know where the end user's request is coming from - I don't want to format the date to the user's locale during SSR服务器不知道最终用户的请求来自哪里——我不想在 SSR 期间将日期格式化为用户的语言环境
...but if there is a difference between the server rendered content and the client rendered content, I get a react-hydration-error ...但是如果服务器呈现的内容和客户端呈现的内容之间存在差异,我会收到react-hydration-error
What is the recommended approach for rendering date strings on both server and client?在服务器和客户端上呈现日期字符串的推荐方法是什么?
You can format the date the server and pass it to the client-side as a prop, then format it again to your desired format using luxon.您可以格式化服务器的日期并将其作为道具传递给客户端,然后使用 luxon 将其再次格式化为您想要的格式。 With this method, you can use the formatted date in your HTML for the Google crawler as well as the user, without any difference in the information received by either.使用此方法,您可以将 HTML 中的格式化日期用于 Google 爬虫和用户,两者收到的信息没有任何差异。 This should also avoid the hydration error.这也应该避免水合作用错误。
Here is an example:这是一个例子:
// server-side:
import { DateTime } from 'luxon';
export async function getServerSideProps() {
const creationDate = DateTime.utc().toISO();
return {
props: {
creationDate,
},
};
}
// client-side:
import { DateTime } from 'luxon';
const Post = ({ creationDate }) => {
const formattedCreationDate = DateTime.fromISO(creationDate)
.setLocale('en-US')
.toLocaleString(DateTime.DATE_FULL);
return (
<>
<p>{formattedCreationDate}</p>
</>
);
};
export default Post;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.