1.定义useLocalStorageSize钩子函数
// 计算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.默认导出
export default useLocalStorageSize;
3.在需要的组件中引入
import useLocalStorageSize from "./Encapsulation/useLocal";
4.设置单位
//设置单位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.使用
const size = useLocalStorageSize();const formattedSize = formatSizeUnits(size);
6.效果