[英]How can I integrate React-Redux with Firebase?
我使用create-react-app
創建了一個反應應用程序,並使用減速器配置了一個 redux 存儲。 我還添加了 firebase,我的項目運行良好。 這些組件可以觸發從 firestore 獲取集合的操作,作為回報,它會更新 redux 存儲。
集成 firebase 和 redux 商店的最佳方式是什么? The way I am currently doing it, is to have a separate action that triggers the fetch/delete/onSnapshot from firebase, and handing a reference to dispatch
so that firebase function can take its time executing the command, then it can call dispatch with an更新商店的操作。
但是我希望我的所有操作都在一個文件中,以便更好(關注點分離)。 因此,firebase 可以調用調度,但動作創建者存在於我的 actions.js 文件中。 這樣,我以后可以決定在單個文件中更改動作名稱,如果我決定這樣做的話。
這種方法的問題是,我需要一個單獨的操作來觸發異步 function 和 firebase,以及另一個操作創建器,用於當 promise 完成時。
什么是我正在做的更好的方法?
const rootReducer = combineReducers({
cards: cardsReducer,
});
const store = createStore( rootReducer , {}, applyMiddleware(thunk));
export default store;
// I need this to be called from an action in actions.js
// therefor, I am exporting it, and also, I am handing it dispatch
// so it will call store.dispatch once data is ready
export const fetchCardsFromFirebase = async (dispatch) => {
const cardsCollection = collection(db, "cards");
const cardsSnapshot = await getDocs(roomsCollection);
const cards = roomsSnapshot.docs.map(doc => ({ ...doc.data(), id: doc.id }));
// here I can either explicitly dispatch an action
/*
dispatch({
type: CARDS_FETCHED //this constant string will have to be imported
payload: cards
});
*/
// or I can let an action in actions.js do the above:
dispatch(cardsFetched(rooms)); //this function is imported from actions.js
}
import { FETCH_CARDS , CARDS_FETCHED } from "./types";
import { fetchCardsFromFirebase } from "../myFirebase";
export const fetchCards = () => async (dispatch) => {
fetchCardsFromFirebase(dispatch); // give firebase access to dispatch
dispatch({
type: FETCH_CARDS,
payload: {message: "fetching cards... please wait"}
});
};
const cardsFetched = (cards) => ({
action: CARDS_FETCHED,
payload: cards
});
一般來說,這是一種非常古老的 Redux - 現代 Redux 不使用 switch..case reducers 或 ACTION_TYPES 並切換到現代 Redux可能已經節省了你的代碼。
也就是說,官方 Redux 工具包 (RTK) 還附帶 RTK-Query,這是一種數據緩存抽象,應該也可以與 firebase 一起正常工作,並且會自動為您生成減速器、動作甚至鈎子。 (提示:使用 firebase 您將需要使用queryFn
)。 這也會為您節省更多代碼。
我建議您遵循官方 Redux 教程,該教程首先展示了現代 Redux,然后在后面的章節中進入 RTK 查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.