在下面的代码中,将数据库变量作为props传递给Router / NavigationProvider提供的所有组件的最佳方法是什么?
import {
createRouter,
NavigationProvider,
StackNavigation,
} from '@exponent/ex-navigation'
const Router = createRouter(() => ({
jobs: () => Jobs,
sample: () => Sample
}))
render () {
const database = this.openDatabase()
<NavigationProvider router={Router}>
<StackNavigation initialRoute={Router.getRoute('home')} />
</NavigationProvider>
}
谢谢!
答案 0 :(得分:-2)
您应该创建一个新的javascript文件,该文件导出您的数据库连接并将其导入您希望使用它的组件中。
您还可以创建更高阶的组件,该组件将数据库连接作为组件的支柱。这类似于ExNavigation中内置的withNavigation
或Redux的React绑定附带的connect
。
然而,由于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()
<强> routes.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
<强> App.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
)}
)
}
}