【问题标题】:TypeError: Cannot read property 'then' of undefined in my custom functionTypeError:无法在我的自定义函数中读取未定义的属性“then”
【发布时间】:2018-12-30 09:59:35
【问题描述】:

我正在开发我的 react-app,我现在正在使用 react-redux-firebase。关注step。我想让它同步并使用 setState() 方法。

显示错误:

TypeError: 无法读取未定义的属性“then”

dbGetDate.js

const dbGetData = (store, col, doc, col2, doc2) => {
    store.firestore.collection(col).doc(doc).collection(col2).doc(doc2).get().then(data => {
            if (data.exists) {
                return new Promise((resolve, reject) => {
                    if(data.data() != null){
                        resolve(data.data());
                    }
                else{
                    reject("Some error in fetching data");
                }

            })

        }
        else {
            return new Promise((resolve, reject) => {
                reject("not such data in record");
            })
        }
        }
    ).catch(function (error) {
        return ("Ops, there should be an error");
    });
}
export default dbGetData;

myPage.js

componentWillMount(){
        const dbStore = dbConnect;
        dbGetData(dbStore, 'Test', '123', 'Member','001')
        .then(data => {
            console.log(data);
            this.setState({
                firebaseData : data
            })
        });

}

【问题讨论】:

    标签: reactjs firebase asynchronous google-cloud-firestore react-redux-firebase


    【解决方案1】:

    您收到该错误的原因是因为函数dbGetData 没有返回任何内容,因此调用它的结果是undefined。如果你希望它返回一个 Promise,你必须在顶层创建 Promise:

     const dbGetData = (store, col, doc, col2, doc2) => {
       const promise = new Promise((resolve, reject) => {
         // ... do stuff
       });
    
       return promise;
     };
    

    【讨论】:

    • 它有效!但是我可以在 if else 块中返回 promise 而不在函数顶部创建 promise 变量吗?
    • 您不能这样做,因为如果 if / else 存在于回调中,那么您将无法在顶级函数中返回承诺。另外,我看不出你为什么要在你的 sn-p 中使用它。
    猜你喜欢
    • 2019-08-19
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 2014-11-29
    • 2016-09-20
    • 1970-01-01
    相关资源
    最近更新 更多