【问题标题】:Reactjs fetch data from firestore when click button单击按钮时Reactjs从firestore获取数据
【发布时间】:2019-11-30 05:11:24
【问题描述】:

当用户单击handleReset() 时,我想从 Firestore 加载数据。当我单击handleReset() 时,它应该从firestore 加载数据并存储在localstorage 中。我正在使用reactjs。错误消息Cannot read property 'map' of undefined

admin.js

  handleReset(e) {
    const products = getDefaultProducts();
    saveProducts(products);
    this.setState({products});
    alert('Product Reset');
  }

product.js

export const getDefaultProducts = () => {

  const ref = firebase.firestore().collection('vouchers').doc('default');
  console.log('ref', ref)
    ref.get().then((doc) => {

      if (doc.exists) {
        return [
          { id: 'v5', qty: doc.data().v5 }, 
          { id: 'v10', qty: doc.data().v10, }, 
          { id: 'v20', qty: doc.data().v20 }, 
          { id: 'v50', qty: doc.data().v50 }, 
          { id: 'v100', qty: doc.data().v100 }
        ];  
      } else {
        console.log("No such document!");
      }
    });
}

export const saveProducts = (products) => {
  products = products.map(prd => {
    prd.qty = isNaN(+prd.qty) ? 0 : prd.qty
    return prd;
  });

  localStorage.setItem(STORAGE_KEY, JSON.stringify(products));
}

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore loaddata


    【解决方案1】:

    答案在您的错误消息中。 products 对象未定义,因为您没有从 getDefaultProducts 返回任何内容。 ref.get().then(... 是一个承诺,因此内部函数(您返回的地方)将在您的函数完成后稍后执行。

    要解决此问题,您必须在 getDefaultProducts 中返回一个 Promise,然后使用适当的 .then 方法访问结果。

    const getDefaultProducts = () => {
        const ref = firebase.firestore().collection('vouchers').doc('default');
        console.log('ref', ref);
        // see we've added a return statement here, to return a Promise from this method
        return ref.get().then((doc) => {
            if (doc.exists) {
                return [
                    { id: 'v5', qty: doc.data().v5 },
                    { id: 'v10', qty: doc.data().v10, },
                    { id: 'v20', qty: doc.data().v20 },
                    { id: 'v50', qty: doc.data().v50 },
                    { id: 'v100', qty: doc.data().v100 }
                ];
            } else {
                throw new Error("No such document!"); // throw error here to cause current promise to be rejected
            }
        });
    }
    
    function handleReset(e) {
        getDefaultProducts().then((products) => {
            saveProducts(products);
            this.setState({ products });
            alert('Product Reset');
        }, (err) => {
            // this will be executed if firestore returns an error or document doesn't exist
            console.log(err);
        });
    }
    

    【讨论】:

    • 您好,需要this question 方面的帮助吗?
    • 谢谢@caesay。像魅力一样工作
    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多