如何在我的React项目中使Firebase可用?

问题描述 投票:0回答:1

因此,我在我的React应用程序中使用Firebase Firestore。我使用下面的代码从Firestore检索已添加到购物车中的物品。

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    firebase
      .firestore()
      .collection(user.displayName)
      .doc("Cart")
      .collection("cartItems")
      .onSnapshot(snapShot => {
        const newItems = snapShot.docs.map(doc => ({
          id: doc.id,
          name: doc.data().name,
          category: doc.data().category,
          MRP: doc.data().MRP,
          shagunPrice: Math.round(doc.data().shagunPrice),
          count: doc.data().count,
        }))
        if (mounted) setItems(newItems)
      })
  }
})

我在useEffect()中使用此代码,因此,如果有任何项目添加到购物车,我就可以更新组件。

useEffect(() => {
   //above code
}, [firebase, cartItems])

但是问题是,出于某些目的,有多个组件和页面需要购物车项目。而且我在所有不符合DRY(不要自己重复)原则的组件和页面上使用相同的代码。

我想做的是在一个地方编写代码,并在我的应用程序中访问购物车项目,并将最新的项目添加到购物车中。

javascript reactjs firebase dry
1个回答
0
投票

您可以尝试使用React中的useContext()。它使您可以在所有不同的App组件中共享状态。这是我制作的一个示例(没有firebase)https://github.com/progamandoconro/React-JS-Native-Apps/tree/master/Context

此处提供官方参考链接:https://reactjs.org/docs/hooks-reference.html

© www.soinside.com 2019 - 2024. All rights reserved.