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

RTK Query转换响应时大写对象键首字母无效问题排查

问题分析与修复

问题原因

你当前的代码只生成了首字母大写的键名字符串,但没有对目标对象做任何修改操作——既没有将旧键的值映射到新键,也没有处理旧键的移除,因此deepCopy对象完全保持原样,自然看不到效果。

修复方案

第一步:定义转换后的类型

由于TypeScript强类型约束,需要先声明首字母大写后的对象类型:

export type CapitalizedBudgetType = {
    Bills: number | null,
    Transportation: number | null,
    Health: number | null,
    School: number | null,
    Food: number | null,
    Entertainment: number | null
};

第二步:修改RTK Query的转换逻辑

推荐使用Object.fromEntries实现更简洁的键名转换:

getBudget: build.query<CapitalizedBudgetType, void>({
    query: () => "budget",
    providesTags: ["Budget"],
    transformResponse: (response: BudgetType) => {
        return Object.fromEntries(
            Object.entries(response).map(([key, value]) => {
                // 生成首字母大写的新键名
                const newKey = key.charAt(0).toUpperCase() + key.slice(1);
                return [newKey, value];
            })
        ) as CapitalizedBudgetType;
    }
}),

如果偏好forEach写法,也可以手动构建新对象:

transformResponse: (response: BudgetType) => {
    const transformed: CapitalizedBudgetType = {
        Bills: null,
        Transportation: null,
        Health: null,
        School: null,
        Food: null,
        Entertainment: null
    };
    Object.keys(response).forEach((key) => {
        const newKey = key[0].toUpperCase() + key.slice(1) as keyof CapitalizedBudgetType;
        transformed[newKey] = response[key as keyof BudgetType];
    });
    return transformed;
}

关键说明

  • 对象的键无法直接重命名,必须通过构建新对象来存储转换后的键值对。
  • 转换后的类型声明是必须的,否则TypeScript会因键名不匹配抛出类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:05:07