[英]RangeError: locale must contain formatDistance property when using locale variable in Next.js with date-fns
I have a website with multiple languages done in Next.js. Next.js provides several methods to get all the locales, here are the following:我在 Next.js 有一个多语言的网站。Next.js 提供了几种获取所有语言环境的方法,如下:
{locale} // current locale in use 'es'
{locales} // all the configured locales in an array [ "en", "de", "es", "ja", "ru" ]
{defaultLocale} // if no locale provided, will use en
Then in my code, i have this date-fns method to get the distance in days for a given date i get from my createdAt value.然后在我的代码中,我有这个 date-fns 方法来获取我从我的 createdAt 值获得的给定日期的天数距离。
// my import languages
import { es, de, ja, en, ru } from 'date-fns/locale';
<BodyOne>
This category was funded{' '}
{formatDistance(new Date(category.createdAt), new Date(), {
locale: locale,
})}
</BodyOne>
This gives me the following error:这给了我以下错误:
RangeError: locale must contain formatDistance property
I don't understand why, this works:我不明白为什么,这有效:
{
locale: es,
})}
But this one with the variable locale doesn't.但是这个具有可变区域设置的却没有。
{
locale: locale,
})}
if I create a new constant, let's say:如果我创建一个新常量,假设:
const myCurrentLang = es;
it works, but if I output:它有效,但如果我 output:
const myCurrentLang = 'es';
I get the error: RangeError: locale must contain formatDistance property我收到错误:RangeError: locale must contain formatDistance property
Maybe i need to convert the 'es' value to other type in order to make date-fns work.也许我需要将“es”值转换为其他类型才能使 date-fns 工作。
the thing is formatDistance is waiting for a namespace
and you're trying to send a string
as a parameter.问题是 formatDistance 正在等待
namespace
,而您正试图发送一个string
作为参数。 When you declared const myCurrentLang = es;
当你声明
const myCurrentLang = es;
it works because es is referring to date-fns/locale's namespace...它之所以有效,是因为 es 指的是 date-fns/locale 的命名空间...
Hope it helps希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.