[英]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.