#ios #iphone #react-native #toast
Вопрос:
Я разрабатываю приложение для Iphone с использованием React Native.На странице входа в систему я настраиваю выходные данные API в хранилище ASYNC(в хранилище) и получаю значения на странице входа для отображения всплывающего сообщения IOS,когда учетные данные неверны.Ниже приведена программа магазина.
auth.js
import AsyncStorage from '@react-native-community/async-storage'; import Device from '../../model/Device'; export const LOGIN ='LOGIN'; export const login=(textemailid,textpassword) =gt;{ //console.log(textemailid " " textpassword); const formData = new FormData(); formData.append('txtUemail',textemailid); formData.append('txtUpass',textpassword); return async dispatch =gt;{ await fetch('https:---------------------/login.php', { method:'post', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: formData }) .then(res =gt; res.text()) .then( (loginresult) =gt;{ var login = loginresult.replace('rnrnrntrntrnt',''); saveDataToStoragelogin(login); }).catch(err =gt;{ console.log(err); }) dispatch({type:LOGIN}); } } const saveDataToStoragelogin = (login) =gt;{ console.log('saveDataToStoragelogin has ' login); AsyncStorage.setItem('userDatalogin',JSON.stringify({ login:login })) }
Ниже приведена страница входа в программу
LoginScreen.js
import React from 'react'; import { ImageBackground, StyleSheet, Text, View ,KeyboardAvoidingView,TouchableOpacity} from "react-native"; import { ScrollView } from "react-native-gesture-handler"; import { TextInput } from 'react-native-paper'; import { useDispatch } from 'react-redux'; import * as authActions from '../../store/actions/auth'; import Icon from 'react-native-vector-icons/FontAwesome5'; import AsyncStorage from '@react-native-community/async-storage'; import Toast from 'react-native-root-toast'; const LoginScreen = props =gt; { const [textemailid, setTextEmailId] = React.useState(''); const [textpassword, setTextPassword] = React.useState(''); const [isLoading,setIsLoading] = React.useState(false); const [error, setError] = React.useState(''); const dispatch = useDispatch(); const [hidePassword,sethidePassword] = React.useState(true); const loginHandler = async () =gt; { let action action = authActions.login( textemailid, textpassword ); setError(null); setIsLoading(true); try{ dispatch(action); //AsyncStorage.clear(); const userDatalogin = await AsyncStorage.getItem("userDatalogin"); const obj = JSON.parse(userDatalogin); console.log(obj); var loginStatus1 = obj.login; console.log('login status is ' loginStatus1); if(loginStatus1 === 'success'){ props.navigation.navigate({routeName:'Home'}); } else if(loginStatus1 === 'Login Failed'){ let toast_success = Toast.show('Wrong Credentials'); } } catch(err){ setError(err.message); console.log(err.message); setIsLoading(false); } }; const getUserInformation = async () =gt; { let action action = authActions.getUserInfo( textemailid ); setError(null); setIsLoading(true); try{ dispatch(action); } catch(err){ setError(err.message); console.log(err.message); setIsLoading(false); } }; return( lt;KeyboardAvoidingView style={styles.container}gt; lt;ImageBackground source={require('../../assets/Iphone_LoginPage.jpeg')} resizeMode="cover" style={styles.image}gt; lt;ScrollViewgt; lt;Text style={styles.texthello}gt;Hello lt;/Textgt; lt;Text style={styles.textagain}gt;Again!lt;/Textgt; lt;View style={styles.textinputemail}gt; lt;TextInput style={styles.textinputemail} label='Email' keyboardType="default" editable={true} autoCapitalize = 'none' value={textemailid} onChangeText={textemailid =gt; setTextEmailId(textemailid)}gt; lt;/TextInputgt; lt;/Viewgt; lt;View style={styles.passwordview} gt; lt;TextInput style={styles.textinputpassword}label='Password' value={textpassword} onChangeText={textpassword =gt; setTextPassword(textpassword)} secureTextEntry = {hidePassword ? true : false}gt; lt;/TextInputgt; lt;TouchableOpacity style={styles.imgicon}gt; lt;Icon name={hidePassword ? 'eye-slash' : 'eye'} size={25} color="black" onPress={() =gt; sethidePassword(!hidePassword)} /gt; lt;/TouchableOpacitygt; lt;/Viewgt; lt;TouchableOpacity onPress={ () =gt; { loginHandler(); getUserInformation(); } } style={styles.roundButton1}gt; lt;/TouchableOpacitygt; lt;Text style={styles.textlogin}gt;Loginlt;/Textgt; lt;TouchableOpacity style={styles.textregister} onPress= {()=gt;props.navigation.navigate('SignUp')} gt; lt;Text style={styles.textregister}gt;Registerlt;/Textgt; lt;/TouchableOpacitygt; lt;TouchableOpacity style={styles.textforgotpassword} onPress= {()=gt;props.navigation.navigate('ForgotPassword')}gt; lt;Text style={styles.textforgotpassword}gt;Forgot Passwordlt;/Textgt; lt;/TouchableOpacitygt; lt;/ScrollViewgt; lt;/ImageBackgroundgt; lt;/KeyboardAvoidingViewgt; ) } const styles = StyleSheet.create({ container: { flex: 1 }, image: { flex: 1, justifyContent: "center" }, texthello: { color: "white", fontSize: 50, fontWeight: "bold", textAlign: "center", right:'10%', top:'100%' }, textagain: { color: "white", fontSize: 50, fontWeight: "bold", textAlign: "center", right:'10%', top:'100%' }, textinputemail:{ position:'absolute', top:'250%', width:'90%', backgroundColor:'transparent', }, passwordview:{ flexDirection:'row' , top:'30%' }, imgicon:{ left:'1200%', top:'63%' }, textinputpassword:{ position:'absolute', top:'800%', width:'90%', backgroundColor:'transparent', }, textlogin:{ position:'absolute', color: "black", fontSize: 50, fontWeight: "bold", left:'50%', top:'375%' }, textregister:{ position:'absolute', color: "black", fontSize: 20, fontWeight: "bold", left:'5%', top:'500%', textDecorationLine: 'underline' }, textforgotpassword:{ position:'absolute', color: "black", fontSize: 20, fontWeight: "bold", left:'50%', top:'500%', textDecorationLine: 'underline' }, roundButton1: { position:'absolute', width: 90, height: 90, justifyContent: 'center', alignItems: 'center', padding: 10, borderRadius: 100, backgroundColor: 'orange', top:'372%', left:'65%' }, }); export default LoginScreen;
After running for first time when I enter wrong credentials,it displays correct toast message as ‘Wrong Credentials’ and will get the following result:
Object { "login": "Login Failed", } login status is Login Failed saveDataToStoragelogin has Login Failed
Later if I put correct credentials, then also getting Wrong credentials toast message with the following result:
Object { "login": "Login Failed", } login status is Login Failed saveDataToStoragelogin has success
After 2-3 clicks I can log into the app with the following result in console
Object { "login": "success", } login status is success saveDataToStoragelogin has success
AsyncStorage не перезаписывает данные в 1-й раз.Может ли кто-нибудь помочь мне получить правильное значение AsyncStorage.Это из-за текстового входа в осязаемую область вместо кнопки?.заранее спасибо.