[英]RangeError: locale must contain formatDistance property when using locale variable in Next.js with date-fns
我在 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
然后在我的代码中,我有这个 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>
这给了我以下错误:
RangeError: locale must contain formatDistance property
我不明白为什么,这有效:
{
locale: es,
})}
但是这个具有可变区域设置的却没有。
{
locale: locale,
})}
如果我创建一个新常量,假设:
const myCurrentLang = es;
它有效,但如果我 output:
const myCurrentLang = 'es';
我收到错误:RangeError: locale must contain formatDistance property
也许我需要将“es”值转换为其他类型才能使 date-fns 工作。
问题是 formatDistance 正在等待namespace
,而您正试图发送一个string
作为参数。 当你声明const myCurrentLang = es;
它之所以有效,是因为 es 指的是 date-fns/locale 的命名空间...
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.