reactjs - React - 如何编写 API 映射器?
问题描述
我正在研究 React 和 TypeScript。并为我糟糕的英语道歉...
我正在尝试制作 Web 服务,并且需要在我的 React 项目(使用 TypeScript)中制作 API 密钥映射器。起初,我的服务器是用 python 编写的,所以键名约定是snake_case
. 但是我使用的是 TypeScript,所以我想为 JSON 编写映射器,而不需要任何模块或类。
我这样写映射器:
// api result: { "hello_world": "hello world!" }
const Mapper = {
HELLO_WORLD: 'hello_world', // snake_case because server is written with python
} as const;
interface APIResult {
[Mapper.HELLO_WORLD]: string;
}
但是,当我必须使用 API 结果对象时,我需要这样写:
// in React components
const text = result[Mapper.HELLO_WORLD]
我认为这是非常丑陋的代码.. API 映射器有没有更好的方法?
解决方案
您可以创建一个清理函数来将 raw_API_Response 转换为您的 expectedAPIResponse ,如下所示:
interface RawResponse {
hello_world: string;
another_world: number;
snack_case_to_camel_case: string;
}
interface expectedResponse {
helloWorld: string;
anotherWorld: number;
snackCaseToCamelCase: string;
}
function sanitizeResponse(raw: RawResponse) : expectedResponse {
const result: expectedResponse = {
helloWorld: raw.hello_world,
anotherWorld: raw.another_world,
snackCaseToCamelCase: raw.snack_case_to_camel_case,
};
return result;
}
console.log(sanitizeResponse({
hello_world: 'string',
another_world: 100,
snack_case_to_camel_case: 'another string'
}));
推荐阅读
- c++ - 如何在 C++ 中使用 setw 在控制台中对齐/格式化文本
- java - 从内存中读取文件:“/sys/class/”和“/dev/”文件夹
- xml - 如何在 Jasper 中从 XML 数据源引用集合字段?
- vba - 如何在对象名称中插入字符?
- reactjs - 如何在基于 typescript (babel) 的 monorepo 中获取 create-react-app 测试
- java - Android:Dagger 2构造函数注入不调用构造函数,最终进入NPE
- typescript - TypeScript 以安全的方式扩展原生对象,例如通过 TS 转换器的扩展函数
- python - 遍历每个单词后如何用换行符返回单词中的字母?
- javascript - 如何在页面加载时激活替换的 HTML 元素?
- c++ - 使用 MQTT 和 C++ 无法解析的外部符号?