【问题标题】:React Native & Firestore: Property 'auth' does not exist on type 'typeof / error object unknownReact Native&Firestore:类型'typeof /错误对象未知的属性'auth'不存在
【发布时间】:2021-11-16 20:45:35
【问题描述】:

我将 typescript 与 Firebase 和 React Native 一起使用。

我在我的注册屏幕上工作,我像这样导入了 firebase:

import * as firebase from 'firebase/app';
import 'firebase/auth';

然后在我的onSignUp 函数中,我得到了这个:

onSignUp = async () => {
  if (this.state.email && this.state.password) {
    try {
      const response = await firebase
        .auth()
        .createUserWithEmailAndPassword(this.state.email, this.state.password);
    } catch (error) {
      if (error.code == 'auth/email-already-in-use') {
        Alert.alert('Signup Error', 'User already exist!', [
          {
            text: 'Ok',
          },
        ]);
      }
    }
  }
};

Visual Studio Code 抱怨 auth 上的 await firebase.auth() 上面写着 Property 'auth' does not exist on type 'typeof

此外,它还抱怨 error.code 并说 Object is of type 'unknown'.ts(2571) 不确定它的含义并被卡了一段时间。

这是我的完整代码:

export interface Props {}
interface State {
  email: string;
  password: any;
  isLoading: boolean;
}

export default class LoginScreen extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      email: '',
      password: '',
      isLoading: false,
    };
  }

  onLogin = () => {};

  onSignUp = async () => {
    if (this.state.email && this.state.password) {
      try {
        const response = await firebase
          .auth()
          .createUserWithEmailAndPassword(
            this.state.email,
            this.state.password
          );
      } catch (error) {
        if (error.code == 'auth/email-already-in-use') {
          Alert.alert('Signup Error', 'User already exist!', [
            {
              text: 'Ok',
            },
          ]);
        }
      }
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          placeholder="Your Email"
          keyboardType="email-address"
          autoCorrect={false}
          style={styles.txtInput}
          onChangeText={(email) => this.setState(email)}
        />
        <TextInput
          placeholder="Your Password"
          secureTextEntry
          style={styles.txtInput}
          onChangeText={(password) => this.setState(password)}
        />
        <TouchableOpacity style={styles.btnLog} onPress={this.onLogin}>
          <Text style={styles.logTxt}>Login</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

知道是什么导致了firebase.auth()error.code 吗?请帮忙。

更新:我尝试按照 v9 指南使用异步等待,但仍然无法正常工作:

import {initializeApp} from 'firebase/app';
import {firebaseConfig} from '../config/config';
import {getAuth, createUserWithEmailAndPassword} from 'firebase/auth';

export interface Props {}
interface State {
  email: string;
  password: any;
  isLoading: boolean;
}

export default class LoginScreen extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      email: '',
      password: '',
      isLoading: false,
    };

    this.initialFirebase();
  }

  initialFirebase = () => {
    initializeApp(firebaseConfig);
  };

  auth = getAuth(this.initialFirebase);

  onLogin = () => {};

  onSignUp = async () => {
    if (this.state.email && this.state.password) {
      try {
        const response = await createUserWithEmailAndPassword(
          auth,
          this.state.email,
          this.state.password,
        );
      } catch (error) {
        if (error.code == 'auth/email-already-in-use') {
          Alert.alert('Signup Error', 'User already exist!', [
            {
              text: 'Ok',
            },
          ]);
        }
      }
    }
  };

【问题讨论】:

    标签: typescript firebase react-native


    【解决方案1】:

    您可能拥有使用新语法的new Modular SDK V9。如果要使用现有语法 (v8),请将导入更改为 compat 版本:

    import firebase from 'firebase/compat/app'
    import 'firebase/compat/auth'
    // import 'firebase/compat/[SERVICE]'
    

    我会推荐upgrading to new SDK,因为它具有一定的性能优势。您可以尝试使用以下语法:

    import { initializeApp } from "firebase/app"
    import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"
    
    const app = initializeApp({...config})
    
    const auth = getAuth(app)
    
    
    // in onSignUp
    createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in 
        const user = userCredential.user;
        // ...
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ..
      });
    

    您可以参考documentation了解更多关于新SDK的信息。

    【讨论】:

    • 谢谢。如何使用新的 Modular SDK V9 做到这一点?
    • error.code 说了一些关于Object is of type 'unknown'.ts(2571) 的事,这也和那个有关吗?
    • @AichiGarcia 你能试试我更新的答案吗?还要保持上面链接的文档打开。它同时具有 v8 和 v9 语法。
    • @AichiGarcia 你能把鼠标悬停在this.initialFirebase 上并分享它的截图吗?
    • @AichiGarcia 似乎代码可以在 this.initialFirebase 实际上具有 FirebaseApp 的值之前运行...只需尝试不带参数的 getAuth()...确保 initializeApp 在此之前运行
    猜你喜欢
    • 1970-01-01
    • 2018-10-13
    • 2019-09-14
    • 2020-02-13
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2020-09-19
    相关资源
    最近更新 更多