如何将西瓜数据库的本地响应从APP传递到组件

时间:2019-11-01 13:16:26

标签: reactjs react-native react-router watermelondb

预先感谢 我目前正在使用西瓜数据库,并且已经按照文档进行了配置。如何将数据库从 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} />

2 个答案:

答案 0 :(得分:1)

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

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

答案 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
    }