1.定义useLocalStorageSize钩子函数
javascript
// 计算localStorage大小
function useLocalStorageSize() {
const [size, setSize] = useState(0);
useEffect(() => {
const calculateSize = () => {
let totalSize = 0;
for (let key in localStorage) {
//过滤掉继承自原型链的属性
if (localStorage.hasOwnProperty(key)) {
// 计算key和value的大小
let keySize = new Blob([key]).size;
let valueSize = new Blob([localStorage[key]]).size;
totalSize += keySize + valueSize;
}
}
setSize(totalSize);
};
// 初始计算一次大小
calculateSize();
//当 localStorage发生变化时,重新计算大小
window.addEventListener("storage", calculateSize);
// 当组件卸载时,移除事件监听
return () => {
window.removeEventListener("storage", calculateSize);
};
}, []);
return size;
}
2.默认导出
javascript
export default useLocalStorageSize;
3.在需要的组件中引入
javascript
import useLocalStorageSize from "./Encapsulation/useLocal";
4.设置单位
javascript
//设置单位
function formatSizeUnits(bytes: any) {
if (bytes >= 1073741824) {
return (bytes / 1073741824).toFixed(2) + " GB";
} else if (bytes >= 1048576) {
return (bytes / 1048576).toFixed(2) + " MB";
} else if (bytes >= 1024) {
return (bytes / 1024).toFixed(2) + " KB";
} else if (bytes > 1) {
return (bytes / 1024).toFixed(2) + " KB";
} else if (bytes === 1) {
return bytes + " byte";
} else {
return "0 bytes";
}
}
5.使用
javascript
const size = useLocalStorageSize();
const formattedSize = formatSizeUnits(size);