【问题标题】:Redux, Firebase, and react-native: fetch data asyncRedux、Firebase 和 react-native:异步获取数据
【发布时间】:2017-05-11 18:02:53
【问题描述】:

我正在使用 Redux 和 Firebase 开发一个 React-native 应用程序。 我的 Firebase 数据库是非规范化的,所以它看起来像:

users:
  user_uid:
    my_posts: [ post_key1, post_key2 ]

posts
  post_key1: { post_details }
  post_key2: { post_details }

我应该如何异步获取数据并将帖子数据发送到 Redux 存储?

我知道 Firebase 方法 .on('value') 和 .once('value'),但我无法编写适当的异步函数/thunk 而不会产生问题。

【问题讨论】:

  • 有什么更新吗?
  • 你是在使用 react-redux-firebase 来集成 redux 和 firebase 吗?

标签: firebase react-native firebase-realtime-database redux react-redux


【解决方案1】:

如果您使用react-redux-firebasereduxFirebase 集成,则使用react-native the v2.0.0 docs show 以及使用native-modules through react-native-firebaseJS SDK 的示例。

通过您展示的结构,在加载用户时使用populate轻松自动加载帖子也可能对您有所帮助。

如果您在owner 下的帖子对象上有用户uid,您可以执行以下操作:

Home.js

import { compose } from 'redux'
import { connect } from 'react-redux'
import { firebaseConnect, populate } from 'react-redux-firebase'

const populates = [
  { child: 'owner', root: 'users' } // replace owner with user object
]

const enhance = compose(
  firebaseConnect([
    // passing populates parameter also creates all necessary child queries
    { path: 'posts', populates }
  ]),
  connect(({ firebase }) => ({
    // populate original from data within separate paths redux
    posts: populate(firebase, 'posts', populates),
  }))
)

const SomeComponent = ({ posts }) => <div>{JSON.stringify(posts, null, 2)}</div>

export default enhance(SomeComponent)

App.js

import { createStore, combineReducers, compose } from 'redux'
import { connect } from 'react-redux'
import { reactReduxFirebase, firebaseReducer } from 'react-redux-firebase'
import firebase from 'firebase'
import Home from './Home' // code above

const firebaseConfig = {} // config from firebase console

// react-redux-firebase config
const rrfConfig = {
  userProfile: 'users' // automatically manage profile
}

// initialize firebase instance
firebase.initializeApp(config) // <- new to v2.*.*

// Add reduxReduxFirebase enhancer when making store creator
const createStoreWithFirebase = compose(
  reactReduxFirebase(firebase, rrfConfig)
)(createStore)

// Add Firebase to reducers
const rootReducer = combineReducers({
  firebase: firebaseStateReducer
})

// Create store with reducers and initial state
const initialState = {}
const store = createStoreWithFirebase(rootReducer, initialState)

const App = () => (
  <Provider store={store}>
   <Home />
  </Provider>
);
ReactDOM.render(<App/>, document.querySelector('#app'));

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 2018-11-07
    • 2022-01-26
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多