在日常开发中,代码优化是一个持续的过程。良好的代码不仅能够提高程序的性能,还能增强代码的可读性和可维护性。本文将通过一个具体的例子,展示如何对一个 TypeScript 项目中的代码进行优化。
背景
假设我们有一个用于生成二维码的组件 CodeUrl
,它需要从后端获取 URL 和命令码,并显示在一个模态框中。初始代码如下:
interface QRProps {
name: string; // 二维码描述文字
open: boolean; // 打开关闭modal
onCancel: () => void; // 关闭modal事件
describe?: string; // 底部文字描述
modalStyle?: Object; // modal自定义样式
baseUrl: string; // url核心链接
okText?: string; // 自定义确定按钮文字
cancelText?: string; // 自定义取消按钮文字
id: string;
}
interface AsyncFuncProps {
getURL: Function;
getCommandCode: Function;
}
interface CommandCodeProps {
result: string;
}
class CodeUrl {
private modal: QRProps;
private setLoading: (loading: boolean) => void;
private setUrl: (url: string) => void;
private setCode: (code: string) => void;
private store: AsyncFuncProps;
constructor(
modal: QRProps,
setLoading: (loading: boolean) => void,
setUrl: (url: string) => void,
setCode: (code: string) => void,
store: AsyncFuncProps,
) {
this.modal = modal;
this.setLoading = setLoading;
this.setUrl = setUrl;
this.setCode = setCode;
this.store = store;
}
async fetch(scene: number, key: string) {
this.setLoading(true);
try {
const baseUrl: string = await this.store.getURL(this.modal.id, scene, key);
const commandCode: CommandCodeProps = await this.store.getCommandCode({
scene: `activity:${scene}`,
activityId: this.modal.id,
path: `page://${ENUMS.path[key]}`,
});
this.setCode(commandCode?.result);
this.setUrl(baseUrl); this.setLoading(false);
} catch (error) {
console.log('🚀 _ file: index.tsx:45 _ CodeUrl _ error:', error);
throw error;
}
}
static create(
modal: QRProps,
setLoading: (loading: boolean) => void,
setUrl: (url: string) => void,
setCode: (code: string) => void,
store: AsyncFuncProps,
) {
return new CodeUrl(modal, setLoading, setUrl, setCode, store);
}
}
优化目标
- 提高代码的可读性:使代码更加简洁、易读。
- 增强类型安全性:明确函数的返回类型,避免潜在的类型错误。
- 改进错误处理:确保在任何情况下都能正确处理错误。
优化步骤
1. 明确类型定义
首先,我们明确 modalStyle
的类型为 React.CSSProperties
,以更准确地表DOM
的css
类型。同时,明确 getURL
和 getCommandCode
的返回类型为 Promise
。
modalStyle?: React.CSSProperties; // modal自定义样式
< ---- >
interface CommandCodeProps {
result: string;
}
interface AsyncFuncProps {
getURL: (id: string, scene: number, key: string) => Promise<string>;
getCommandCode: (params: { scene: string; activityId: string; path: string }) => Promise<CommandCodeProps>;
}
2. 改进错误处理
添加 finally
块来确保 setLoading(false)
总是被执行,无论请求成功还是失败。
3. 简化代码
id
可以从modal
中解构出来,在 fetch
方法中,直接解构 getCommandCode
的返回值 result
,使代码更简洁。在getCommandCode
方法中,可以把组装数据的逻辑存放在方法函数里面,这样子的话页面代码看起来会更加美观。
async fetch(scene: number, key: string) {
const { getURL, getCommandCode } = this.store; ;
const { id } = this.modal
this.setLoading(true);
try {
const baseUrl: string = await getURL(id, scene, key);
const { result } = await getCommandCode(scene, activityId, key);
this.setCode(result);
this.setUrl(baseUrl); this.setLoading(false);
} catch (error) {
console.log('🚀 _ file: index.tsx:45 _ CodeUrl _ error:', error);
throw error;
}
}
< ----在store文件中---- >
async getCommandCode(scene, activityId, key) {
try {
const res = await api.getCommandCode({
scene: `partner:${scene}`,
activityId,
path: `page://${ENUMS.path[key]}`,
});
return res;
} catch (error) {
console.log('🚀 _ file: PartnerStore.js:171 _ PartnerStore _ error:', error);
throw error;
}
}
最终代码
经过上述优化,最终的代码如下:
interface QRProps {
name: string; // 二维码描述文字
open: boolean; // 打开关闭modal
onCancel: () => void; // 关闭modal事件
describe?: string; // 底部文字描述
modalStyle?: Object; // modal自定义样式
baseUrl: string; // url核心链接
okText?: string; // 自定义确定按钮文字
cancelText?: string; // 自定义取消按钮文字
id: string;
}
interface AsyncFuncProps {
getURL: (activityId: string, key: string, scene: number) => Promise<string>;
getCommandCode: (scene: number, inviteCode: UserProps, key: string) => Promise<CommandCodeProps>;
}
interface CommandCodeProps {
result: string;
}
class CodeUrl {
private modal: QRProps;
private setLoading: (loading: boolean) => void;
private setUrl: (url: string) => void;
private setCode: (code: string) => void;
private store: AsyncFuncProps;
constructor(
modal: QRProps,
setLoading: (loading: boolean) => void,
setUrl: (url: string) => void,
setCode: (code: string) => void,
store: AsyncFuncProps,
) {
this.modal = modal;
this.setLoading = setLoading;
this.setUrl = setUrl;
this.setCode = setCode;
this.store = store;
}
async fetch(scene: number, key: string) {
const { getURL, getCommandCode } = this.store; ;
const { id } = this.modal
this.setLoading(true);
try {
const baseUrl: string = await getURL(id, scene, key);
const { result } = await getCommandCode(scene, activityId, key);
this.setCode(result);
this.setUrl(baseUrl);
this.setLoading(false);
} catch (error) {
console.log('🚀 _ file: index.tsx:45 _ CodeUrl _ error:', error);
throw error;
}
}
static create(
modal: QRProps,
setLoading: (loading: boolean) => void,
setUrl: (url: string) => void,
setCode: (code: string) => void,
store: AsyncFuncProps,
) {
return new CodeUrl(modal, setLoading, setUrl, setCode, store);
}
}
结论
通过上述优化,我们不仅提高了代码的可读性和类型安全性,还增强了错误处理的能力。这些优化措施有助于我们在未来的开发中减少潜在的错误,提高代码的维护性。希望本文对你有所帮助!