0

在此先感谢我目前正在使用西瓜数据库,并且我已根据文档对其进行了配置。如何将数据库从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);

应用程序.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} />
4

2 回答 2

3

您可以尝试通过导入来解决此问题。

index.js

  export const adapter = new SQLiteAdapter({
    dbName: "myDB",
    schema: mySchema 
    });   
  export const database = new Database({
    adapter,
    modelClasses: [dbModel],
    actionsEnabled: true,
    });

mytable.js

import { database } from "index file path" // ex) '../../index.js'
database.collections
于 2019-11-01T18:42:15.530 回答
3

您可以使用与使用 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/hooks';

    const WrappedComponent = () => {
    const database = useDatabase();
    ...etc
    }
于 2019-12-02T15:57:09.013 回答