如何从登录页面获取用户名并在 React Native 的所有页面(组件)上动态使用它

How Do I get the username from Login Page and use it dynamically on all pages (Components) in React Native

我有这个挑战。我想利用从登录组件获得的用户名,一旦用户登录并成功验证,它应该保存用户名,以便它可以在应用程序的所有页面上使用。我是 React Native 开发的新手,所以我不太熟悉会话的使用。

我想知道如何保存登录表单中的用户名,以便我可以在应用程序的所有页面中使用它。我尝试做类似

的事情
  switch(key)
  {
      case "BVN":
         this.props.navigation.navigate('bvn',{user: this.state.user});
          break;
      case "Transfers":
            this.props.navigation.navigate('Transfers',{user: this.state.user});
            break;
      case "Bill Payments":
        this.props.navigation.navigate('BillPayments');
            break;
      case "Checkbook Requests":
            this.props.navigation.navigate('CheckBookRequest');
            break;
      case "Airtime Purchase":
            this.props.navigation.navigate('AirtimePurchase');
            break;
      case "Contact Us":
            this.props.navigation.navigate('Contact');
            break;
  }

因此它可以使用其他页面上的状态,但是,当我使用 getParam 获取用户时,它没有显示任何内容。为什么会这样?

在这种情况下我需要帮助。

编辑

这就是我想要实现的目标

//Login

Login = async() =>
{
    if(username =='james_hall' && password=='qasim1234'){
        await AsyncStorage.setItem(this.state.username,'1');
        this.props.navigation.navigate('Home');
    }else
    {
        alert('Username or Password is invalid');
    }
}

//在 Transfers 页面上获取帐户,以便我可以在 Picker 中使用

 LoadAccountNumber = async() =>
    {
        const AccountNum = await AsyncStorage.getItem(this.state.username); //gotten from saved state
        //make GET request to fetch Details
        
           var searchAPIURL = 'https://uncoiled-crust.000webhostapp.com/api/searchData.php?AccountNum='+AccountNum;
         var header = {
             'Accept': 'application/json',
             'Content-Type': 'application/json'
         };
    
         fetch(
             searchAPIURL,
             {
                 method : 'GET',
                 headers : header
             }
         ).then((response) => response.json())
          .then((responseJson)=> {
              this.setState({Fullname:responseJson[0].Fullname});
              this.setState({balance:responseJson[0].balance});
              this.setState({AccountNum:responseJson[0].AccountNum});
          })
    
    }

声明状态和所有之后。它仍然是 returns Null。我会根据要求分享我的源代码。如果需要

多多指教

您可以使用 AsyncStorage 在您的应用重新启动时存储和访问用户信息,并决定是导航到主屏幕还是登录屏幕

const setItem = async (user) => {
        try {
            await AsyncStorage.setItem("user", JSON.stringify(user));
            console.log('data stored');
        } catch (error) {
            // Error saving data
            console.log('AsyncStorage save error: ' + error.message);
        }
};

实际上,如果您想要用户名甚至在用户从内存中杀死您的应用程序后,您需要像我们上面提到的那样使用``ÀsyncStorage```。那是个缺点,你的app会占用手机一些内存。

如果你只想要会话的用户名,也就是说,你的用户名在登录后在应用程序的任何地方都可用,但是当他从内存中杀死应用程序时,用户名将不再存在。为此,您可以使用 redux。这是一个很大的话题,所以看看link,你可以问我什么。

根据您的上下文来发现您必须使用哪个库:)。

等待您的反馈。谢谢 :).