【问题标题】:Property 'accessToken' does not exist on type 'User' && firebase is not defined类型 \'User\' 上不存在属性 \'accessToken\' && firebase 未定义
【发布时间】:2022-11-07 20:09:06
【问题描述】:

我在我的 React 应用程序中使用 TypeScript,但出现错误“'用户'类型上不存在属性'accessToken'”当获得accessToken 的用户时

我在组件中的处理函数:

const handleRegister = (email: string, password: string) => {
  const auth = getAuth();

  createUserWithEmailAndPassword(auth, email, password)
    .then(({user}) => {
      dispatch(setUser({
        email: user.email,
        token: user.accessToken,
        id: user.uid
      }));
    });
}

在寻找解决此问题的方法后,我这样做了

token: (user as unknown as OAuthCredential).accessToken,

并且 IDE 自动添加了以下导入

import firebase from "firebase/compat";
import OAuthCredential = firebase.auth.OAuthCredential;

但在那之后我在控制台中得到一个错误“未捕获的 ReferenceError:未定义 firebase”. 我觉得很愚蠢,但我不明白如何解决它

【问题讨论】:

  • accessToken 属性确实存在于响应中,但在User 接口和documentation 中都缺少。最好也将问题发布到Github

标签: reactjs typescript firebase firebase-authentication


【解决方案1】:

这样做看看你得到什么结果,我认为你需要 result.user.accessToken 但我不确定

signInWithEmailAndPassword(auth, email, password)
   .then((result: any) => {
     // Signed in 
     console.log(result)
     // ...
})

【讨论】:

  • 通过console.log()我看到用户有财产访问令牌
  • 改为添加(result: any)
【解决方案2】:

我没有对此进行测试,但您可以使用如下所示的内容。

const handleRegister = (email: string, password: string) => {
  const auth = getAuth();

  createUserWithEmailAndPassword(auth, email, password)
    .then(({user}) => {
     user.getIdToken().then(function(idToken) {
       // Send token to your backend via HTTPS
        dispatch(setUser({
          email: user.email,
          token: idToken,
          id: user.uid
        }));
       // ...
     }).catch(function(error) {
       // Handle error
     });
      
    });
}

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 2018-07-30
    • 2021-03-14
    • 1970-01-01
    • 2018-01-29
    • 2020-05-01
    • 2020-08-23
    • 2021-11-04
    相关资源
    最近更新 更多