预先感谢 我目前正在使用西瓜数据库,并且已经按照文档进行了配置。如何将数据库从 index.js 传递到组件
index.js
import { AppRegistry } from 'react-native';
import {App} from './App';
import { name as appName } from './app.json';
import { Database } from "@nozbe/watermelondb";
import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite";
import { dbModel } from "./src/model"
import { mySchema } from "./src/model/schema"
const adapter = new SQLiteAdapter({
dbName: "myDB",
schema: mySchema
});
const database = new Database({
adapter,
modelClasses: [dbModel],
actionsEnabled: true,
});
AppRegistry.registerComponent(appName, () => App);
App.js
import * as React from 'react';
import { Provider } from 'react-redux';
import { AppWithSidebar } from './src/components';
import configureStore from './src/store/configureStore';
const store = configureStore();
export default () => (
<Provider store={store} >
<AppWithMenu/>
</Provider >
);
在App.js中,我有我的Route及其组件。我如何将数据库从index.js传递到组件屏幕。我还需要将其传递到组件屏幕的路由中,并且路由看起来像
<Route path="/mytable" component={TableScreen} />
答案 0 :(得分:1)
您可以尝试通过导入来解决此问题。
export const adapter = new SQLiteAdapter({
dbName: "myDB",
schema: mySchema
});
export const database = new Database({
adapter,
modelClasses: [dbModel],
actionsEnabled: true,
});
import { database } from "index file path" // ex) '../../index.js'
database.collections
答案 1 :(得分:1)
您可以使用与redux相同的逻辑。
import DatabaseProvider from '@nozbe/watermelondb/DatabaseProvider';
import { Database } from "@nozbe/watermelondb";
import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite";
const adapter = new SQLiteAdapter({
dbName: "myDB",
schema: mySchema
});
const database = new Database({
adapter,
modelClasses: [dbModel],
actionsEnabled: true,
});
<DatabaseProvider database={database}>
<Provider store={store} >
<AppWithMenu/>
</Provider >
</DatabaseProvider>
然后在任何包装好的组件中使用钩子:
import { useDatabase } from '@nozbe/watermelondb/src/hooks';
const WrappedComponent = () => {
const database = useDatabase();
...etc
}