Javascript 单击按钮时从firestore获取数据
当用户单击Javascript 单击按钮时从firestore获取数据,javascript,reactjs,firebase,google-cloud-firestore,loaddata,Javascript,Reactjs,Firebase,Google Cloud Firestore,Loaddata,当用户单击handleReset()时,我想从firestore加载数据。当我单击handleReset()时,它应该从firestore加载数据并存储在localstorage中。我用的是reactjs。错误消息无法读取未定义的属性“map” admin.js handleReset(e){ const products=getDefaultProducts(); 储蓄产品(产品);; this.setState({products}); 警报(“产品重置”); }答案在您的错误消息中pro
handleReset()
时,我想从firestore加载数据。当我单击handleReset()时,它应该从firestore加载数据并存储在localstorage中。我用的是reactjs。错误消息无法读取未定义的属性“map”
admin.js
handleReset(e){
const products=getDefaultProducts();
储蓄产品(产品);;
this.setState({products});
警报(“产品重置”);
}
答案在您的错误消息中products
对象未定义,因为您没有从getDefaultProducts
返回任何内容。ref.get()。then(…
是一个承诺,因此内部函数(返回的地方)将在函数完成后执行
要解决此问题,必须在getDefaultProducts
中返回承诺,然后使用适当的。然后使用方法访问结果
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);
});
}
你好,需要帮助吗?谢谢@caesay。工作很有魅力