如何使用next-intl获取指定的数组对象元素?
问题
我的messages/en.json内容如下(注:原内容存在语法错误):
{ "items": [{ "name: "item 1", "price: "100", }, { "name: "item 2", "price: "200", }] }
对应的page.tsx代码:
import { useTranslations } from 'next-intl'; export default function ProductSection() { const t = useTranslations() as any; return <> {t('items[0].price')} </>; }
我还试了另一种写法:
import { useTranslations } from 'next-intl'; export default function ProductSection() { const t = useTranslations('items') as any; return <> {t('[0].price')} </>; }
但两种写法都报错:
IntlError: MISSING_MESSAGE: Could not resolve `items[0].price` in messages for locale `en`.
我不需要循环数组,只想直接获取指定位置的元素。
解决办法
- 先修正JSON语法错误
原JSON里的键名引号未闭合,且存在多余的尾逗号,这会导致next-intl无法正确解析消息。修正后的正确JSON:
{ "items": [ { "name": "item 1", "price": "100" }, { "name": "item 2", "price": "200" } ] }
- 使用next-intl支持的路径语法取值
next-intl不支持[]式的数组索引写法,需要用.来访问数组元素:
- 方法一:完整路径访问
import { useTranslations } from 'next-intl'; export default function ProductSection() { const t = useTranslations(); return <> {t('items.0.price')} </>; }
- 方法二:指定命名空间后访问
import { useTranslations } from 'next-intl'; export default function ProductSection() { const t = useTranslations('items'); return <> {t('0.price')} </>; }
另外,建议不要用as any断言useTranslations的返回值,配置next-intl的类型支持可以获得准确的类型提示,避免不必要的错误。
内容的提问来源于stack exchange,提问作者aboutjquery
相关产品推荐
相关产品推荐

