Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击按钮时从firestore获取数据_Javascript_Reactjs_Firebase_Google Cloud Firestore_Loaddata - Fatal编程技术网

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。工作很有魅力