我正在使用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而不会产生问题。
答案 0 :(得分:1)
如果您使用react-redux-firebase
将redux
与Firebase
集成,the v2.0.0
docs show使用react-native与示例一起使用native-modules through react-native-firebase或{{3} }}
根据您显示的结构,在加载用户时使用JS SDK自动轻松加载帖子也可能会有所帮助。
如果uid
下的帖子对象上有用户owner
,您可以执行以下操作:
<强> 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'));