Javascript Firebase实时数据库-如何构造初始加载和侦听器
我正在使用Firebase实时数据库在React Redux中编写一个应用程序用于存储,并希望加载初始数据,同时在数据更改时接收更新。所需的数据工作流程是:Javascript Firebase实时数据库-如何构造初始加载和侦听器,javascript,reactjs,firebase,firebase-realtime-database,react-redux,Javascript,Reactjs,Firebase,Firebase Realtime Database,React Redux,我正在使用Firebase实时数据库在React Redux中编写一个应用程序用于存储,并希望加载初始数据,同时在数据更改时接收更新。所需的数据工作流程是: 从Firebase实时数据库加载初始数据 填充Redux存储并加载UI 从Firebase实时数据库接收数据库更新 更新Redux存储和组件 到目前为止,我已经完成了第1步和第2步,现在我正在考虑什么是数据库更改数据更新的最佳实践 在我目前的代码中,我调用了一系列api函数来检索初始数据 const setInitialStore = ()
const setInitialStore = () => {
return dispatch => Promise.all([
dispatch(startSetUser()),
dispatch(startSetNotes()),
...
])
}
//** ACTION ***
export const setNotes = (notes) => ({
type: SET_NOTES,
notes
})
//async action, fetch data and dispatches SET_NOTES
export const startSetNotes = () => {
//thunk gives access to store-methods dispatch and getState
return (dispatch, getState) => {
const apiInstruction = { action: DB_ACTION_GET_SUBSCRIBE, payload: null, uid: getState().auth.uid }
//returns a promise
return noteAPI(apiInstruction)
.then((notes) => {
//get data into redux
dispatch(setNotes(notes))
})
}
}
//** REDUCER
const notesReducerDefaultState = []
const notesReducer = (state = notesReducerDefaultState, action) => {
switch (action.type) {
case SET_NOTES:
//returning new array, don't care about what's instate
return action.notes;
...
}
}
//** noteAPI - action "DB_ACTION_GET_SUBSCRIBE" section ***
database.ref(`${dbPath}`).on('value', (snapshot) => {
const notes = []
//parse data
snapshot.forEach((childSnapshot) => {
const note = {
id: childSnapshot.key,
...childSnapshot.val()
}
const noteModel = new NoteModel(note, uid)
notes.push(noteModel.reduxStoreObj)
})
//return notes
resolve(notes)
})
下面解释上述代码结构
setInitialStore - dispatches the action from "setNote"
startSetNote - calls the API that fetches data for action generator
noteAPI - Calls Firebase Realtime Database ".on()" and returns all notes
setNote - Action generator called with collection from database
但这种方法有一个关键缺陷——当Firebase实时数据库更新时,存储将不会得到更新(
侦听器仅在noteAPI内触发,因此永远不会被分派到存储区
对于获取和更新数据,建议的最佳实践是什么?
我是否应该只使用“.once()”获取初始数据,然后使用“.once()”编写单独的代码来处理侦听器?在这种情况下,该代码将“存活”在哪里
换句话说,我如何构造代码,以便Firebase实时数据库侦听器自动更新Redux存储
我已经阅读了关于读写的文档