gpt4 book ai didi

react-native - ExNavigation : how to pass props to all router components?

转载 作者:行者123 更新时间:2023-12-03 15:03:24 25 4
gpt4 key购买 nike

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

谢谢!

最佳答案

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

您还可以创建高阶组件,将数据库连接作为组件的 Prop 。这类似于 withNavigation内置于 ExNavigation 或 connect它带有 Redux 的 React 绑定(bind)。

然而,由于 HOC 是一个有点高级的话题(但不难掌握!)这里是一个没有它的例子。

服务/数据库.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
)}
)
}
}

关于react-native - ExNavigation : how to pass props to all router components?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40009877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com