没有从函数[React Native]获得任何返回值

问题描述 投票:0回答:2

我有这个菜单,我在用户登录时过滤按钮,我从一个单独的文件访问一个功能,检查用户是否被记录。

从菜单

import { IsLogged } from '../GlobalFunctions';

const SubDrawer1 = ({ data, onChange }) => (
    <View>
    {
        IsLogged() ? (
            <View>
                <TouchableOpacity onPress={()=>{onChange('LogoutScreen')}}>
                    <Text>Logout</Text>
                </TouchableOpacity>
            </View>
        ) : (<View />)
    }     
    </View>
);
export default SubDrawer1;

来自GlobalFunctions

export function IsLogged(){
    AsyncStorage.getItem('userId').then((userId) => {
        return userId ? true : false
    })
}

从菜单我调用IsLogged()函数,但当我调试时,它的值是undefined.log它。它应该返回truefalse

function react-native return-value
2个回答
0
投票

您正在尝试调用异步函数,因此您需要添加一些额外的代码。请尝试以下方法。

SubDrawer1

import { Text, View, TouchableOpacity } from "react-native";

import React, { Component } from "react";
import { IsLogged } from "../GlobalFunctions";

const SubDrawer1 = async ({ data, onChange }) => {
  const status = await IsLogged();
  if (status === true) {
    return (
      <View>
        <View>
          <TouchableOpacity
            onPress={() => {
              onChange("LogoutScreen");
            }}
          >
            <Text>Logout</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  } else {
    return (
      <View>
        <View />
      </View>
    );
  }
};

export default SubDrawer1;

'IsLogged()'全局函数

export function async IsLogged(){
    let userId = await AsyncStorage.getItem('userId');
    return userId ? true : false
}

'SubDrawer1'使用类

...

import SubDrawer1 from "./SubDrawer1"; // import your 'SubDrawer1' component

var subDrawer1Component; // declare a variable for your rendering component

//Your main class
export default class ClassName extends Component<Props> {

  componentDidMount() {
    this.getComponentInfo(); //Call this method to get function
  }

  getComponentInfo = async () => {
    subDrawer1Component = await SubDrawer1();// Will take the component
    this.setState({ isDataGet: true });
  };

  render() {
    return (
        ...

        {subDrawer1Component}

        ...
    );
  }

}

...

0
投票

因为AsyncStorage需要一些时间,并且在该功能完成执行之前。 (因为JS中的所有内容都是异步的)

所以只要让它等到它完成一个项目,

export function async IsLogged(){
    let userId = await AsyncStorage.getItem('userId');
    return userId ? true : false
}
© www.soinside.com 2019 - 2024. All rights reserved.