这个问题是在 GitHub 上提出的,答案是“嘿,你听说过 Stack Overflow 这个网站吗?你应该在那里问这个问题!”。
所以我在这里问一个问题!React Native 支持索引数据库吗?
react-native
时,是否必须放弃索引数据库支持?或者,索引数据库可以开箱即用吗?回答上述问题的原因是什么? Indexed DB 不起作用只是因为我们不在浏览器中并且 React Native 目前没有实现该 API 吗?我们可以在 React Native 中填充 Indexed DB 吗?或者,我们应该为这个平台转向替代的持久性方法吗?
我作为技术主管提出这个问题,想知道
react-native
对于我们团队来说是容易还是困难的过渡。
Pouchdb可以在任何支持indexeddb或webSQL(如果不支持)的浏览器中工作。 在react-native pouchdb上有一个适配器可以连接到sqlLit。
在任何环境下您的代码都是相同的。
expo-sqlite
,但它有时确实会变得不稳定,而且他们的API很难使用。我必须包装它,以便我可以使其与异步等待一起工作。
expo-sqlite
和
dexie
一起使用。无需弹出
db.ts
import Dexie, { Table } from 'dexie';
import { Platform } from 'react-native';
import * as SQLite from 'expo-sqlite';
import setGlobalVars from 'indexeddbshim/dist/indexeddbshim-noninvasive';
const win = {};
if (Platform.OS !== 'web') {
setGlobalVars(win, {
checkOrigin: false,
win: SQLite,
deleteDatabaseFiles: false,
useSQLiteIndexes: true,
});
}
export interface Friend {
id?: number;
name: string;
age: number;
}
export class IndexDb extends Dexie {
friends!: Table<Friend>;
constructor() {
super('mydb', {
// The indexedDB and IDBKeyRange are provided by the indexeddbshim
indexedDB: Platform.OS === 'web' ? window.indexedDB : win.indexedDB,
IDBKeyRange: Platform.OS === 'web' ? window.IDBKeyRange : win.IDBKeyRange,
});
this.version(1).stores({
friends: '++id, name, age', // Primary key and indexed props
});
}
}
export const db = new IndexDb();
package.json
"expo-sqlite": "~13.2.2",
"indexeddbshim": "^13.0.0",
"react-native": "0.73.4",
"expo": "~50.0.8",
"dexie": "^3.2.5",
"dexie-react-hooks": "^1.1.7",
sampleComponent.tsx
export default function App() {
const friends = useLiveQuery(() => db.friends.toArray());
const addFriend = () => {
db.friends.add({ name: 'John', age: 25 });
};
return (
<Box w="$full" h="$full" justifyContent="center">
<Center>
<Button onPress={addFriend}>
<Text>Add a friend</Text>
</Button>
{friends?.map((friend) => <Text key={friend.id}>{friend.name}</Text>)}
</Center>
</Box>
);
}