项目中使用 localStorage 获取数据缓存
需求背景
在项目中,我们经常需要存储一些数据,比如不经常变动的字典项,下拉框中的数据等。这些数据可以缓存到 localStorage
中,这样可以提高应用的响应速度,减少网络请求。
实现方案
为了实现 localStorage
的管理,我们可以定义一个 Storage
类,提供以下功能:
1. 类定义
class Storage
定义了一个名为 Storage
的类。
2. getStorage
方法
async getStorage(key) {
const result = localStorage.getItem(key);
if (result) {
return JSON.parse(result);
}
const { data } = await this.getData()
this.setStorage(key, JSON.stringify(data));
return data;
}
async getStorage(key)
:定义了一个异步方法getStorage
,用于获取存储在localStorage
中的数据。const result = localStorage.getItem(key);
:尝试从localStorage
中获取指定key
的数据。if (result) { return JSON.parse(result); }
:如果数据存在,则将其解析为 JSON 格式并返回。const { data } = await this.getData()
:如果localStorage
中没有数据,则调用getData
方法从外部获取数据。this.setStorage(key, JSON.stringify(data));
:将获取到的数据存储到localStorage
中。return data;
:返回获取到的数据。
3. setStorage
方法
setStorage(key, value) {
localStorage.setItem(key, value);
}
setStorage(key, value)
:定义了一个方法setStorage
,用于将数据存储到localStorage
中。localStorage.setItem(key, value);
:将value
存储到localStorage
中,键为key
。
4. getData
方法
async getData() {
/**
* axios 请求数据
* 这里是假数据,实际项目中应该请求后端接口获取数据
* 这里返回的数据格式应该是 { data: xxx }
*/
}
async getData()
:定义了一个异步方法getData
,用于从外部获取数据。- 注释中提到,实际项目中应该使用
axios
请求后端接口获取数据,这里返回的数据格式应该是{ data: xxx }
。
代码总结
这段代码的主要功能是提供一个 Storage
类,用于管理数据的存储和获取。具体功能如下:
-
数据获取:
- 首先尝试从
localStorage
中获取数据。 - 如果
localStorage
中没有数据,则从外部获取数据(通过getData
方法),并将其存储到localStorage
中。
- 首先尝试从
-
数据存储:
- 提供
setStorage
方法,用于将数据存储到localStorage
中。
- 提供
-
外部数据获取:
- 提供
getData
方法,用于从外部获取数据(实际项目中应通过后端接口获取数据)。
- 提供
通过这些功能,Storage
类能够有效地管理数据的缓存和获取,减少对外部数据源的频繁请求,提高应用的性能和响应速度。
Answer
好的,以下是对代码的优化和改进:
- 减少不必要的计算:在
getStorage
方法中,如果localStorage
中已经存在数据,则直接返回,避免不必要的网络请求。 - 去除冗余代码:代码已经比较简洁,没有明显的冗余代码。
- 增加适当的错误处理机制:在
getStorage
和getData
方法中增加错误处理,确保在网络请求失败或解析数据失败时能够捕获并处理错误。
优化后的代码如下:
class Storage {
// 获取存储
async getStorage(key) {
try {
const result = localStorage.getItem(key);
if (result) {
return JSON.parse(result);
}
const { data } = await this.getData();
this.setStorage(key, JSON.stringify(data));
return data;
} catch (error) {
console.error('Error in getStorage:', error);
throw error;
}
}
// 设置存储
setStorage(key, value) {
try {
localStorage.setItem(key, value);
} catch (error) {
console.error('Error in setStorage:', error);
throw error;
}
}
// 获取数据
async getData() {
try {
// 这里应该是实际的 axios 请求
// const response = await axios.get('your-api-endpoint');
// return response.data;
// 假数据
return { data: 'fakeData' };
} catch (error) {
console.error('Error in getData:', error);
throw error;
}
}
}
主要改进点:
- 错误处理:在
getStorage
、setStorage
和getData
方法中增加了try-catch
块,捕获并处理可能的错误。 - 日志记录:在捕获到错误时,使用
console.error
记录错误信息,便于调试和排查问题。 - 假数据:在
getData
方法中保留了假数据的注释,实际项目中应替换为真实的axios
请求。