我有一个博览会 react 应用程序的以下代码,除了我最近添加的附加代码 - 'isLoggedIn' 结构外,该应用程序已按预期工作。我添加了注释,即输出了第一个 console.log,但是“等待”内的部分似乎从未运行。为什么是这样?我的代码目的是检查 securestorage 中是否存在 token ,如果存在则是否有效。如果是这样,导航到“ListsView”。它在模拟器上运行,但如上所述,不运行等待中的代码。
import React, { Component, useState } from 'react';
import * as Font from 'expo-font';
import { StyleSheet, Text, View , Button, TextInput, Alert} from 'react-native';
import { AppLoading } from 'expo';
import { Formik } from 'formik';
import { globalStyles } from '../styles/global';
import * as SecureStore from 'expo-secure-store';
const getFonts = () => Font.loadAsync({
'lobster': require('../assets/fonts/Lobster-Regular.ttf'),
'nunito': require('../assets/fonts/Nunito-Regular.ttf')
});
export default function LogInForm({ navigation }) {
const [fontsLoaded ,setFontsLoaded] = useState(false);
const goToLists = () => {
navigation.navigate('ListsView');
}
const isLoggedIn = () => {
console.log("-------------"); **NOTE THIS IS TRIGGERED**
(async () => {
console.log("xxxxxxxxxx"); **THIS IS NEVER TRIGGERED**
const token = await SecureStore.getItemAsync('token');
// Your fetch code
this.setState({loaded:false, error: null});
let url = 'https://www.myWebsite.com/api/auth/isLoggedIn';
let h = new Headers();
h.append('Authorization', `Bearer ${token}`);
h.append('Content-Type', 'application/json');
h.append('X-Requested-With', 'XMLHttpRequest');
let req = new Request(url, {
headers: h,
method: 'GET'
});
fetch(req)
.then(response=>response.json())
.then(this.setState({token: isSet}));
console.log(token);
console.log("**************");
})
}
if(fontsLoaded){
isLoggedIn();
return(
<View style={globalStyles.container}>
<View style={globalStyles.centering}>
<Text style={globalStyles.titleText}>OurShoppingList</Text>
<View style={globalStyles.logInScreen}>
<Text style={globalStyles.headingText}>Log In</Text>
<View>
<Formik
initialValues={{ email: '', password: ''}}
onSubmit={(values) => {
SecureStore.deleteItemAsync('token');
fetch('https://www.myWebsite.com/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({
email: values.email,
password: values.password,
}),
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson)
if(responseJson.access_token){
const setToken = async (token) => {
await SecureStore.setItemAsync('token', responseJson.access_token);
};
setToken ();
navigation.navigate('ListsView');
} else {
Alert.alert(responseJson.message);
}
})
.catch(error => {
console.error(error);
alert(error.message);
});
if(SecureStore.getItemAsync('token')!='') {
goToLists;
}
}}
>
{(props) => (
<View>
<Text style={globalStyles.labelText}>Email Address:</Text>
<TextInput
autoCompleteType="username"
style={globalStyles.textInput}
onChangeText={props.handleChange('email')}
value={props.values.email}
/>
<Text style={globalStyles.labelText}>Password:</Text>
<TextInput secureTextEntry={true}
style={globalStyles.textInput}
onChangeText={props.handleChange('password')}
value={props.values.password}
/>
<View style={globalStyles.buttons}>
<Button title='submit' color='orange' onPress={props.handleSubmit} />
</View>
</View>
)}
</Formik>
</View>
</View>
</View>
<View style={globalStyles.login}>
</View>
</View>
)
} else {
return (
<AppLoading
startAsync={getFonts}
onFinish={() => setFontsLoaded(true)}
/>
);
}
}
最佳答案
以 (async () => {
endend with })
开头的代码块仅创建一个函数,但无法实际运行它。向其附加 ()
将运行该函数。
所以将其更改为如下所示:
(async () => {
console.log("xxxxxxxxxx");
...
...
})()
注意末尾的()
,它将触发函数调用。
关于javascript - Await 内的代码未在 Expo App 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65533135/