【问题标题】:Firebase and React Object is possibly 'null'. TS2531Firebase 和 React 对象可能为“空”。 TS2531
【发布时间】:2020-06-08 19:03:03
【问题描述】:

我正在 react 和 firebase 中开发应用程序,当我尝试在数据库中写入时显示此错误,我不知道为什么:

对象可能是“空”。 TS2531 它标记了这段代码

export async function registerUser(email: string, password: string, name:string, lastname: string, phoneNumber: string){
    firebase.auth().createUserWithEmailAndPassword(email,password).then(cred => {
        return db.collection('users').doc(cred.user.uid).set({
                                          ^
            'name': name,
            'lastname': lastname,
            'phone-number': phoneNumber
        })
    }).then(() => {
        redirectTo('/login')
    })

【问题讨论】:

    标签: typescript firebase null firebase-authentication


    【解决方案1】:

    createUserWithEmailAndPassword 的 API 文档中可以看出,cred 是一个 UserCredential 对象。该文档建议其 user 属性可以为空。在这种情况下它是否可以 ever 为 null 无关紧要 - TypeScript 建议您无论如何都应该检查它以避免可能的崩溃。所以,就这样做吧:

    firebase.auth().createUserWithEmailAndPassword(email,password).then(cred => {
        const user = cred.user
        if (user) {
            // use user safely here
        }
    })
    

    【讨论】:

    • 太棒了!在 Stack Overflow 上,习惯上使用答案左侧的按钮来投票和接受有用的答案。
    • 我的声望不够 :( 抱歉!我是新来的
    • 每个人都应该能够接受自己问题的正确答案。这是左边的复选标记。
    • 哦,我忘了。我以为你的意思是向上箭头按钮
    猜你喜欢
    • 2021-02-14
    • 2021-08-27
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2019-11-23
    相关资源
    最近更新 更多