使用react-indexed-db新增object store后部分浏览器未生成,是否与IndexedDB版本有关
问题描述
我使用react-indexed-db库操作浏览器IndexedDB以存储数据。
我最初发布网站时,仅配置了一个object store,配置文件为src/config/DBConfig.js,内容如下:
export const DBConfig = { name: "bookDB", version: 1, objectStoresMeta: [ { store: "reads", storeConfig: { keyPath: "hash", autoIncrement: false }, storeSchema: [ { name: "hash", keypath: "hash", options: { unique: true } }, { name: "token", keypath: "token", options: { unique: true } }, { name: "sa", keypath: "sa", options: { unique: false } }, { name: "ss", keypath: "ss", options: { unique: false } }, ], } ], };
今日我在同一数据库中新增了object store,配置修改为如下内容:
export const DBConfig = { name: "bookDB", version: 1, objectStoresMeta: [ { store: "reads", storeConfig: { keyPath: "hash", autoIncrement: false }, storeSchema: [ { name: "hash", keypath: "hash", options: { unique: true } }, { name: "token", keypath: "token", options: { unique: true } }, { name: "sa", keypath: "sa", options: { unique: false } }, { name: "ss", keypath: "ss", options: { unique: false } }, ], }, { store: "books", storeConfig: { keyPath: "hash", autoIncrement: false }, storeSchema: [ { name: "hash", keypath: "hash", options: { unique: true } }, { name: "token", keypath: "token", options: { unique: true } }, ], }, ], };
以下是调用两类数据库对象的示例代码:
import React, { useEffect, useState } from "react"; import axios from "axios"; import { initDB, useIndexedDB } from "react-indexed-db"; import { DBConfig } from "../config/DBConfig"; initDB(DBConfig); const BookRead = (props) => { const readsObject = useIndexedDB("reads"); const booksObject = useIndexedDB("books"); const [storedRead, setStoredRead] = useState(); const [data, setData] = useState(); useEffect(() => { readsObject .getByIndex("hash", props.match.params.id) .then((data) => { setStoredRead(data); }) .catch((e) => {}); }, []); const readRequest = (token) => { axios .post(`${process.env.REACT_APP_API_URL}book/read`, { name: readerName(), token: token, }) .then((res) => { if (res.data.token) { booksObject.add({ hash: props.match.params.id, token: res.data.token, }); readsObject.add({ hash: props.match.params.id, token: res.data.token, ss: "", sa: "", }); } else { setData(res.data); } }) .catch((error) => { console.log(error); }); }; return <div>Book Content</div>; }; export default BookRead;
目前实测在部分浏览器中可看到新增的books object store已创建,但在另一部分浏览器中未生成该存储。
请问该问题是否与IndexedDB的schema版本有关?
问题解答
是的,该问题完全和IndexedDB的版本规则直接相关。
IndexedDB 只有在传入的数据库版本号高于当前浏览器本地已存在的数据库版本时,才会触发升级回调(onupgradeneeded),执行新增 object store、修改索引等结构变更逻辑。你当前的配置里数据库版本仍然为 1,和最初上线时的版本完全一致,浏览器会直接判定数据库结构无变更,不会触发升级流程,自然不会创建新增的books store。
你观察到的部分浏览器正常创建了books store,原因是这些浏览器本地原本不存在bookDB这个数据库,首次打开站点时会直接用你最新的完整配置初始化所有 object store;而未生成该存储的浏览器,本地已经存在版本为 1 的bookDB数据库,版本没有提升,因此不会执行新增 store 的逻辑。
修复方案
- 直接将
DBConfig中的version字段从 1 修改为 2 - 确保项目中没有其他位置传入更低的数据库版本号
- 本地测试时如果旧数据库残留导致异常,可直接清除站点的 IndexedDB 缓存后重新验证
内容的提问来源于stack exchange,提问作者Q8root
相关产品推荐
相关产品推荐

