我正在开发一个应用程序,该应用程序要在Firebase中使用电子邮件和密码对用户进行身份验证。我已经在Firebase控制台中启用了电子邮件和密码登录方法。在运行该应用程序时,我遇到类型错误“ _this.setState不是函数。下面是我的代码。请检查并指导我。谢谢。
我的App.js
import React from "react";
import FirebaseKeys from "./config";
import * as firebase from "firebase";
export default () => {
const [isLoading, setIsLoading] = React.useState(true);
React.useEffect(() => {
setTimeout(() => {
setIsLoading(false);
}, 2000);
}, []);
state = {
loggedIn: null,
};
var firebaseConfig = FirebaseKeys;
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({
loggedIn: true,
});
} else {
this.setState({
loggedIn: false,
});
}
});
if (isLoading) {
return <Loading />;
}
return (
<NavigationContainer>
{loggedIn ? <DrawerScreen /> : <AuthStackScreen />}
</NavigationContainer>
);
};
LogginScreen.js
import firebase from "firebase";
export const SignIn = ({ navigation }) => {
state = {
email: "",
password: "",
errorMessage: null,
};
handleLogin = () => {
const { email, password } = this.state;
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch((error) => this.setState({ errorMessage: error.message }));
};
return (
<View style={styles.form}>
<View>
<Text style={styles.inputTitle}>Email Address</Text>
<TextInput
style={styles.input}
autoCapitalize="none"
onChangeText={(email) => this.setState({ email })}
value={this.state.email}
></TextInput>
</View>
<View style={{ marginTop: 32 }}>
<Text style={styles.inputTitle}>Password</Text>
<TextInput
style={styles.input}
secureTextEntry
autoCapitalize="none"
onChangeText={(password) => this.setState({ password })}
value={this.state.password}
></TextInput>
</View>
</View>
<TouchableOpacity style={styles.button} onPress={this.handleLogin}>
<Text style={{ color: "#FFF", fontWeight: "500" }}>Sign in</Text>
</TouchableOpacity>
<TouchableOpacity
style={{ alignSelf: "center", marginTop: 32 }}
onPress={() => navigation.push("SignUp")}
>
<Text style={{ color: "#414959", fontSize: 13 }}>
New to SocialApp?{" "}
<Text style={{ fontWeight: "500", color: "#E9446A" }}>Sign up</Text>
</Text>
</TouchableOpacity>
</View>
);
};
答案 0 :(得分:1)
您的App组件是功能组件,因此this.setState不存在,您应该改用useState。
import React from "react";
import FirebaseKeys from "./config";
import * as firebase from "firebase";
export default () => {
const [isLoading, setIsLoading] = React.useState(true);
const [loggedIn, setLoggedIn] = React.useState(false);
React.useEffect(() => {
setTimeout(() => {
setIsLoading(false);
}, 2000);
}, []);
state = {
loggedIn: null,
};
var firebaseConfig = FirebaseKeys;
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
setLoggedIn(true)
} else {
setLoggedIn(false)
}
});
if (isLoading) {
return <Loading />;
}
return (
<NavigationContainer>
{loggedIn ? <DrawerScreen /> : <AuthStackScreen />}
</NavigationContainer>
);
};