【发布时间】: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