javascript - Await 内的代码未在 Expo App 中运行

标签 javascript react-native promise expo token

我有一个博览会 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/

相关文章:

javascript - 使用 $http 上传文件

react-native - 如何检查已安装的React-Native版本

javascript - useSelector() 返回未定义

javascript - 在 promise 中打开窗口

javascript - 使用 promise 在下一个 promise 中使用返回值编写 while 循环

javascript - 当数据来自数据库时,如何在javascript中一次仅选择一个单选按钮并取消选择其他单选按钮?

javascript - Stomp 客户端订阅创建新数组 javascripts

javascript - MongoDB 与 Node.js 说 "Unexpected token"

android - react native 键盘将 Bottom Sheet 推出屏幕/顶部

javascript - 使用 Promise 对象返回函数的值