6

在下面的代码中,将数据库变量作为 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>
}

谢谢!

4

1 回答 1

-1

您应该创建一个新的 javascript 文件,该文件导出您的数据库连接并将其导入您希望使用它的组件中。

您还可以创建高阶组件,将数据库连接作为组件的道具。这类似于withNavigationExNavigation 中内置的或connectRedux 的 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
      )}
    )
  }
}
于 2016-10-15T18:51:52.540 回答