You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中基于i18next翻译值对JSON下拉选项按字母排序的问题

问题根因

你遇到的两个异常分别是语法错误和数据结构适配错误:

  1. [].concat(item.options?)报错是因为可选链语法书写错误,正确写法是item?.options,问号要跟在待判断的属性前面而非后面。同时直接用>/<比较翻译后的字符串不符合多语言排序规则,会出现乱序。
  2. 第二种写法出现随机数字是因为你把item.options的数组结构当成了对象结构处理:Object.entries()传入数组时,会返回[[下标1, 值1], [下标2, 值2]]的结构,你把数组下标当成了翻译key,自然会输出数字。

修复方案

直接对item.options数组做处理,先校验存在性,再用localeCompare传入当前i18n语言做排序即可,修复后代码如下:

// 注意要先在当前文件引入你初始化好的i18n实例
import i18n from '你的i18n初始化文件路径'

const createField = (parentName: string, item: any) => {
  const field = {
    type: `${item.type}`, 
    name: `${parentName ?? ''}${parentName?.length ? '.' : ''}${item.name}`,
    label: t(`${item.label ?? item.name}`), 
    properties: {
      placeholder: `${item.placeholder ?? ''}`
    } as any,
  };
        
  if (item.type === 'select' && Array.isArray(item?.options)) {
    field.properties = {
      ...field.properties,
      // 先拷贝原数组避免修改原数据,再按翻译后的值排序
      options: [...item.options].sort((a, b) => {
        // 用i18n当前语言做本地化排序,适配不同语言的排序规则
        // 如果你的排序依据是翻译后的value字段值,把下方的t(a.label)替换为t(a.value)即可
        return t(a.label).localeCompare(t(b.label), i18n.language)
      }).map((option: any) => ({
        label: t(option.label),
        value: option.value
      }))
    };
  };
  return field; // 你原来的代码片段漏了返回field的逻辑,记得补上
};

额外注意

代码中增加了Array.isArray校验,避免item.options不存在或者不是数组时抛出异常。

内容的提问来源于stack exchange,提问作者Stacey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 05:36:00