您应该创建一个新的 javascript 文件,该文件导出您的数据库连接并将其导入您希望使用它的组件中。
您还可以创建高阶组件,将数据库连接作为组件的道具。这类似于withNavigation
ExNavigation 中内置的或connect
Redux 的 React 绑定附带的。
然而,由于 HOC 是一个有点高级的话题(但不难掌握!)这里是一个没有它的例子。
服务/database.js
// Open database connection here and export it like any other module.
// The following is pseudo code to illustrate example
import { database } from 'database'
export default database.connect()
路由.js
import Jobs from './containers/Jobs'
import Sample from './containers/Sample'
import { createRouter } from '@exponent/ex-navigation'
const Router = createRouter(() => ({
jobs: () => Jobs,
sample: () => Sample
}))
export default Router
应用程序.js
import React from 'react'
import {
NavigationProvider,
StackNavigation,
} from '@exponent/ex-navigation'
const App = () => (
<NavigationProvider router={Router}>
<StackNavigation initialRoute={Router.getRoute('home')} />
</NavigationProvider>
)
export default App
容器/Jobs.js
import React, { Component } from 'react'
// Import database connection in every container component you wish to use it
import databaseConnection from '../services/database'
export default class Jobs extends Component {
state = {
jobs: []
}
componentDidMount() {
databaseConnection
.get('jobs')
.then(jobs => this.setState({ jobs }))
}
render() {
return (
{this.state.jobs.map(job =>
// Render jobs
)}
)
}
}