У меня проблема с моим старым проектом React Native: когда я пытаюсь войти в систему, используя учетные данные, расположенные в моей базе данных, появляется эта ошибка:
LOG {"assets": [], "createdAt": "2024-05-08T22:05:09.403Z", "extra": {"eas": {}, "expoClient": {"_internal": [Объект], "android": [Объект], "assetBundlePatterns": [Массив], "description": "", "hostUri": "192.168.0.0:8081", "icon": "./assets/icon.png", "iconUrl": "http://192.168.0.0: 8081/assets/./assets/icon.png", "ios": [Объект], "имя": "StoreApp", "ориентация": "портрет", "платформы": [Массив], "плагины": [ Array], «sdkVersion»: «51.0.0», «slug»: «StoreApp», «splash»: [Object], «userInterfaceStyle»: «light», «version»: «1.0.0», «web» : [Object]}, "expoGo": {"__flipperHack": "Упаковщик React Native запущен", "debuggerHost": "192.168.0.0:8081", "developer": [Object], "mainModuleName": "node_modules\ expo\AppEntry", "packagerOpts": [Object]}, "scopeKey": "@anonymous/StoreApp-35d629ed-671c-45b1-9842-dd2299cf867f"}, "id": "910ccd44-7756-42de-9292-d7b1c1fea05f ", "launchAsset": {"contentType": "application/javascript", "key": "bundle", "url": "http://192.168.0.0:8081/node_modules%5C ... ?platform= ios&dev=true&hot=false&transform.engine=hermes&transform.bytecode=true&transform.routerRoot=app"}, "metadata": {}, "runtimeVersion": "exposdk:51.0.0">
Ошибка входа: [TypeError: Невозможно прочитать свойство «включено» для неопределенного]
пробовал задать вопрос в чате, но в моем случае это не помогло. Если вам нужна дополнительная информация, не стесняйтесь спрашивать
это для моего старшего проекта
Спасибо
за дополнительную помощь:
код loginscreen.js:
import React, { useState, useEffect } from "react";
import {
View,
Text,
TextInput,
TouchableOpacity,
StyleSheet,
ImageBackground,
Image,
Alert,
KeyboardAvoidingView,
Platform,
ActivityIndicator,
} from "react-native";
import { useFormik } from "formik";
/* import * as Yup from "yup";
*/ import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
const LoginScreen = () => {
const navigation = useNavigation();
const initialValues = {
email: "",
password: "",
};
const navigateToStore = () => {
navigation.reset({ index: 0, routes: [{ name: "AppStack" }] });
};
/* const validationSchema = Yup.object().shape({
email: Yup.string()
.email("Invalid email address")
.required("Email is required"),
password: Yup.string().required("Password is required"),
}); */
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isLoggingIn, setIsLoggingIn] = useState(false);
const handleLogin = async (values) => {
try {
setIsLoggingIn(true);
//send the login data to the backend
const userData = {
email: values.email,
password: values.password,
};
//make a POST request to the backend API for user login
const response = await fetch("http://192.168.0.0:8081/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
const data = await response.json();
console.log(data);
//check if login was successful
if (response.ok) {
if (data.user.enabled === 0) {
//user account is disabled
Alert.alert(
"Account Disabled",
"Contact us at SweetyCandy@support.com."
);
} else {
//save the isLoggedIn state to AsyncStorage
await AsyncStorage.setItem("isLoggedIn", "true");
await AsyncStorage.setItem("userId", data.user.userId.toString());
await AsyncStorage.setItem("token", JSON.stringify(data));
setIsLoggedIn(true);
navigateToStore();
}
} else {
console.log("Login failed. Invalid credentials.");
Alert.alert("Login Failed.", "Invalid Credentials. Please try again.");
}
} catch (error) {
console.error("Error logging in:", error);
} finally {
setIsLoggingIn(false);
}
};
const formik = useFormik({
initialValues,
/* validationSchema,
*/ onSubmit: handleLogin, //use the handleLogin function to handle form submission
});
if (isLoggedIn) {
//return null if the user is already logged in
return null;
}
return (
{isLoggingIn ? (
) : (
Login
)}
OR
navigation.navigate("RegistrationScreen")}
>
Sign Up
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
paddingHorizontal: 20,
},
input: {
width: "100%",
height: "8%",
borderWidth: 1,
borderColor: "gray",
paddingHorizontal: 10,
backgroundColor: "white",
borderRadius: 15,
marginBottom: 10,
},
button: {
backgroundColor: "#2980B9",
paddingVertical: 12,
paddingHorizontal: 25,
borderRadius: 30,
},
buttonText: {
color: "white",
fontSize: 18,
fontWeight: "bold",
},
/* errorText: {
color: "#ECF0F1",
marginBottom: 5,
}, */
logo: {
width: 270,
height: 170,
marginBottom: 70,
},
orContainer: {
flexDirection: "row",
alignItems: "center",
marginVertical: 10,
},
orLine: {
flex: 1,
height: 3,
backgroundColor: "#2980B9",
},
orText: {
color: "white",
marginHorizontal: 10,
fontSize: 20,
fontWeight: "bold",
},
signupButton: {
backgroundColor: "white",
paddingVertical: 12,
paddingHorizontal: 20,
borderRadius: 30,
marginTop: 10,
},
signupButtonText: {
color: "#2980B9",
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
},
loadingContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
export default LoginScreen;
Подробнее здесь: https://stackoverflow.com/questions/784 ... -undefined
Ошибка входа в систему: [TypeError: невозможно прочитать свойство «включено» из неопределенного] ⇐ Android
Форум для тех, кто программирует под Android
1715207172
Anonymous
У меня проблема с моим старым проектом React Native: когда я пытаюсь войти в систему, используя учетные данные, расположенные в моей базе данных, появляется эта ошибка:
LOG {"assets": [], "createdAt": "2024-05-08T22:05:09.403Z", "extra": {"eas": {}, "expoClient": {"_internal": [Объект], "android": [Объект], "assetBundlePatterns": [Массив], "description": "", "hostUri": "192.168.0.0:8081", "icon": "./assets/icon.png", "iconUrl": "http://192.168.0.0: 8081/assets/./assets/icon.png", "ios": [Объект], "имя": "StoreApp", "ориентация": "портрет", "платформы": [Массив], "плагины": [ Array], «sdkVersion»: «51.0.0», «slug»: «StoreApp», «splash»: [Object], «userInterfaceStyle»: «light», «version»: «1.0.0», «web» : [Object]}, "expoGo": {"__flipperHack": "Упаковщик React Native запущен", "debuggerHost": "192.168.0.0:8081", "developer": [Object], "mainModuleName": "node_modules\ expo\AppEntry", "packagerOpts": [Object]}, "scopeKey": "@anonymous/StoreApp-35d629ed-671c-45b1-9842-dd2299cf867f"}, "id": "910ccd44-7756-42de-9292-d7b1c1fea05f ", "launchAsset": {"contentType": "application/javascript", "key": "bundle", "url": "http://192.168.0.0:8081/node_modules%5Cexpo%5CAppEntry.bundle?platform= ios&dev=true&hot=false&transform.engine=hermes&transform.bytecode=true&transform.routerRoot=app"}, "metadata": {}, "runtimeVersion": "exposdk:51.0.0">
Ошибка входа: [TypeError: Невозможно прочитать свойство «включено» для неопределенного]
пробовал задать вопрос в чате, но в моем случае это не помогло. Если вам нужна дополнительная информация, не стесняйтесь спрашивать
это для моего старшего проекта
Спасибо
за дополнительную помощь:
код loginscreen.js:
import React, { useState, useEffect } from "react";
import {
View,
Text,
TextInput,
TouchableOpacity,
StyleSheet,
ImageBackground,
Image,
Alert,
KeyboardAvoidingView,
Platform,
ActivityIndicator,
} from "react-native";
import { useFormik } from "formik";
/* import * as Yup from "yup";
*/ import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
const LoginScreen = () => {
const navigation = useNavigation();
const initialValues = {
email: "",
password: "",
};
const navigateToStore = () => {
navigation.reset({ index: 0, routes: [{ name: "AppStack" }] });
};
/* const validationSchema = Yup.object().shape({
email: Yup.string()
.email("Invalid email address")
.required("Email is required"),
password: Yup.string().required("Password is required"),
}); */
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isLoggingIn, setIsLoggingIn] = useState(false);
const handleLogin = async (values) => {
try {
setIsLoggingIn(true);
//send the login data to the backend
const userData = {
email: values.email,
password: values.password,
};
//make a POST request to the backend API for user login
const response = await fetch("http://192.168.0.0:8081/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
const data = await response.json();
console.log(data);
//check if login was successful
if (response.ok) {
if (data.user.enabled === 0) {
//user account is disabled
Alert.alert(
"Account Disabled",
"Contact us at SweetyCandy@support.com."
);
} else {
//save the isLoggedIn state to AsyncStorage
await AsyncStorage.setItem("isLoggedIn", "true");
await AsyncStorage.setItem("userId", data.user.userId.toString());
await AsyncStorage.setItem("token", JSON.stringify(data));
setIsLoggedIn(true);
navigateToStore();
}
} else {
console.log("Login failed. Invalid credentials.");
Alert.alert("Login Failed.", "Invalid Credentials. Please try again.");
}
} catch (error) {
console.error("Error logging in:", error);
} finally {
setIsLoggingIn(false);
}
};
const formik = useFormik({
initialValues,
/* validationSchema,
*/ onSubmit: handleLogin, //use the handleLogin function to handle form submission
});
if (isLoggedIn) {
//return null if the user is already logged in
return null;
}
return (
{isLoggingIn ? (
) : (
Login
)}
OR
navigation.navigate("RegistrationScreen")}
>
Sign Up
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
paddingHorizontal: 20,
},
input: {
width: "100%",
height: "8%",
borderWidth: 1,
borderColor: "gray",
paddingHorizontal: 10,
backgroundColor: "white",
borderRadius: 15,
marginBottom: 10,
},
button: {
backgroundColor: "#2980B9",
paddingVertical: 12,
paddingHorizontal: 25,
borderRadius: 30,
},
buttonText: {
color: "white",
fontSize: 18,
fontWeight: "bold",
},
/* errorText: {
color: "#ECF0F1",
marginBottom: 5,
}, */
logo: {
width: 270,
height: 170,
marginBottom: 70,
},
orContainer: {
flexDirection: "row",
alignItems: "center",
marginVertical: 10,
},
orLine: {
flex: 1,
height: 3,
backgroundColor: "#2980B9",
},
orText: {
color: "white",
marginHorizontal: 10,
fontSize: 20,
fontWeight: "bold",
},
signupButton: {
backgroundColor: "white",
paddingVertical: 12,
paddingHorizontal: 20,
borderRadius: 30,
marginTop: 10,
},
signupButtonText: {
color: "#2980B9",
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
},
loadingContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
export default LoginScreen;
Подробнее здесь: [url]https://stackoverflow.com/questions/78451398/error-logging-in-typeerror-cannot-read-property-enabled-of-undefined[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия