// 请求列表数据 getList() { if (this.projectState == 0) { // this.loading = true; listCompletedDaily(this.queryParams).then((response) => { dailyFollowList({ userId: this.userId }).then((res) => { itemTabs.forEach(item => { const isFollowed = itemList.some(entry => entry.followedId == item.userId); item.followed = isFollowed; // 根据匹配结果设置 true 或 false }); this.materialList = response.rows; this.total = response.total; this.loading = false; }); }); } else if (this.projectState == 1) { this.loading = true; getNotSubmittedApi(this.queryParams).then((response) => { this.materialList = response.rows; this.total = response.total; this.loading = false; }); } else if (this.projectState == 2) { this.loading = true; getUnFollowApi(this.queryParams).then((response) => { this.materialList = response.rows; this.total = response.total; this.loading = false; }); } }, 代码优化
时间: 2025-04-07 15:10:28 浏览: 56
这段代码的核心逻辑是根据不同条件 (`this.projectState`) 调用不同的 API 并处理返回的数据。以下是优化后的代码及其详细解析。
---
### 优化后的代码
```javascript
getList() {
let fetchDataFunction; // 定义一个变量用于存储具体的API调用方法
switch (this.projectState) {
case 0:
fetchDataFunction = () =>
listCompletedDaily(this.queryParams).then(response =>
dailyFollowList({ userId: this.userId }).then(res => {
itemTabs.forEach(item => {
const isFollowed = itemList.some(entry => entry.followedId === item.userId);
item.followed = isFollowed; // 设置关注状态
});
return response;
}));
break;
case 1:
fetchDataFunction = () => getNotSubmittedApi(this.queryParams);
break;
case 2:
fetchDataFunction = () => getUnFollowApi(this.queryParams);
break;
default:
throw new Error('Invalid project state'); // 异常情况抛出错误提示
}
this.loading = true; // 统一开启加载状态
fetchDataFunction()
.then(response => {
this.materialList = response.rows; // 更新列表数据
this.total = response.total; // 更新总数
})
.catch(error => {
console.error('Error fetching data:', error); // 错误日志记录
})
.finally(() => {
this.loading = false; // 统一关闭加载状态
});
}
```
---
### 优化思路解析
1. **提取公共逻辑**
将不同条件下都有的操作如 `this.loading = true` 和 `this.loading = false` 提取到外部统一管理,避免重复书写相同的逻辑。
2. **封装异步调用**
使用函数指针的方式(即定义 `fetchDataFunction` 变量)来保存实际的异步调用方法,并将其从主流程中抽离出来。这种做法不仅可以简化代码结构,也便于扩展新的功能而无需改动原有逻辑。
3. **增强可读性和可维护性**
利用 `switch-case` 结构替代嵌套 `if-else` ,使得分支更加清晰直观;同时在每个 branch 内部只负责指定特定的行为(如确定需要使用的 api 函数),进一步分解职责。
4. **添加默认异常处理路径**
在原版代码里缺少针对未知状态值时如何响应的规定,在这里我们引入了一个简单的报错机制以应对非法输入场景,保证程序稳健运行。
5. **链式调用改进**
对于项目状态为 0 的复杂情形下进行了重构,采用更连贯地 Promise 链接形式表达多重依赖关系,保持整体风格一致的同时也让意图更为明了。
---
阅读全文
相关推荐



















