簡體   English   中英

如何異步加載firebase數據到react-redux?

[英]How do I load firebase data into react-redux asynchronously?

我目前正在嘗試將我的產品數據加載到 redux 中,但到目前為止,我似乎無法將從 firestore 返回的產品信息傳遞到 reducer 中。

Index.js -> 在創建商店后立即從 firestore 加載前 10 個產品。

store.dispatch(getAllProducts)

動作/index.js

import shop from '../api/shop'

const receiveProducts = products => ({
  type: types.RECEIVE_PRODUCTS
  products
})

const getAllProducts = () => dispatch => {
  shop.getProducts(products => {
     dispatch(receiveProducts)
  })
}

商店.js

import fetchProducts from './firebase/fetchProducts'

export default {
   getProducts: (cb) => cb(fetchProducts())
}

fetchProducts.js文件

const fetchProducts = async() => {
   const ProductList = await firebase_product.firestore()
      .collection('store_products').limit(10)

   ProductList.get().then((querySnapshot) => {
      const tempDoc = querySnapshot.docs.map((doc) => {
         return { id: doc.id, ...doc.data() }
      })
   }).catch(function (error) {
      console.log('Error getting Documents: ', error)
   })
}

在產品減速器中

const byId = (state={}, action) => {
   case RECEIVE_PRODUCTS: 
      console.log(action); <- this should be products, but it is now promise due to aysnc function return?
}

我可以毫無問題地獲取文檔(tempDocs 毫無問題地獲取前 10 個文檔。)但我無法將數據傳回我的 redux。如果我正在創建普通的 React 應用程序,我會在檢索時添加加載 state來自 firestore 的文件,我是否也需要在 redux 中做類似的事情?

抱歉,如果代碼目前看起來很亂。

fetchProducts是一個異步 function 所以你需要在調用dispatch之前等待它的結果。 有幾種方法可以做到這一點,您可以讓fetchProducts通過鈎子訪問dispatch或直接將 dispatch 傳遞給fetchProducts

我不太了解shop.js的用途,但您也可以await fetchProducts ,然后將其結果傳遞給 dispatch。

我用來完成這個的通用例程:

const ListenGenerator = (sliceName, tableName, filterArray) => {
  return () => {
    //returns a listener function
    try {
      const unsubscribe = ListenCollectionGroupQuery(
        tableName,
        filterArray,
        (listenResults) => {
          store.dispatch(
            genericReduxAction(sliceName, tableName, listenResults)
          );
        },
        (err) => {
          console.log(
            err + ` ListenGenerator listener ${sliceName} ${tableName} err`
          );
        }
      );
      //The unsubscribe function to be returned includes clearing
      // Redux entry
      const unsubscriber = () => {
        //effectively a closure
        unsubscribe();
        store.dispatch(genericReduxAction(sliceName, tableName, null));
      };

      return unsubscriber;
    } catch (err) {
      console.log(
        `failed:ListenGenerator ${sliceName} ${tableName} err: ${err}`
      );
    }
  };
};

ListenCollectionGroupQuery聽起來像; 它需要一個tableName ,一個 filter/.where() 條件數組和 data/err 回調。

genericReduxAction幾乎只是連接 sliceName 和 TableName 來創建一個動作類型(我的縮減器以類似的方式解構動作類型)。 重點是您可以將分派放入數據回調中。

除此之外,您只需將 Redux 視為 Redux - 訂閱、獲取等,就好像數據完全是本地的一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM