如何在另一个屏幕上访问asyncStorage的密钥

时间:2019-01-06 13:18:30

标签: javascript android reactjs react-native redux

我的应用中有一些AsyncStorage问题,

我需要在其他屏幕上使用用户名存储的值 现在,当我登录到屏幕并转到主屏幕时,我需要获取项目存储并向他们展示其工作正常,但是注销并删除密钥后, 它会将我移至登录屏幕的右侧,但是在刷新应用程序时,它将其移至主屏幕,并在2秒后几乎将我导航至登录屏幕,如何在应用程序的首次运行中不这样做

这是我的两个屏幕的代码,

登录屏幕

import React, { Component } from "react";
import {
  StyleSheet,
  View,
  StatusBar,
  Text,
  TextInput,
  TouchableOpacity,
  AsyncStorage
} from "react-native";
export default class Login extends Component {
  constructor() {
    super();
    this.state = {
      username: "",
      password: ""
    };
  }

  componentDidMount() {
    const login = AsyncStorage.getItem("@myApp:username");
    if (login == null) {
      this.props.navigation.navigate("Login");
    } else {
      this.props.navigation.navigate("Home");
    }
  }
  _onLogin = () => {
    let username = this.state.username;
    let password = this.state.password;
    if (username !== "" && password !== "") {
      AsyncStorage.setItem("@myApp:username", this.state.username).then(
        username => {
          this.setState({ username: username });
        }
      );
      this.props.navigation.navigate("Home");
      console.log(`username is ${username}`);
    } else {
      this.props.navigation.navigate("Login");
    }
  };
  render() {
    return (
      <View style={styles.container}>
        <StatusBar backgroundColor="#333" barStyle="light-content" />
        <Text style={{ fontSize: 28, margin: 10 }}>Login</Text>
        <TextInput
          placeholder="Username"
          onChangeText={username => {
            this.setState({ username: username });
          }}
          value={this.state.username}
          autoCorrect={false}
          returnKeyType="next"
          style={{
            padding: 10,
            margin: 15,
            borderBottomColor: "#333",
            borderBottomWidth: 1,
            width: "80%"
          }}
          editable={true}
        />
        <TextInput
          placeholder="Password"
          onChangeText={password => {
            this.setState({ password: password });
          }}
          secureTextEntry={true}
          value={this.state.password}
          autoCorrect={false}
          returnKeyType="next"
          style={{
            padding: 10,
            margin: 15,
            borderBottomColor: "#333",
            borderBottomWidth: 1,
            width: "80%"
          }}
          editable={true}
        />

        <TouchableOpacity
          style={{
            margin: 20,
            padding: 10,
            width: "70%",
            backgroundColor: "#1a73e8"
          }}
          onPress={this._onLogin}
        >
          <Text style={{ color: "#FFF", textAlign: "center", fontSize: 18 }}>
            Log In
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff"
  }
});

主屏幕

import React, { Component } from "react";
import {
  StyleSheet,
  View,
  ImageBackground,
  Text,
  AsyncStorage,
  TouchableOpacity
} from "react-native";
export default class Home extends Component {
  constructor() {
    super();
    this.state = {
      name: ""
    };
  }
  async componentDidMount() {
    try {
      const storedValue = await AsyncStorage.getItem("@myApp:username");
      this.setState({ name: storedValue });
      if (storedValue == null) {
        this.props.navigation.navigate("Login");
      }
      console.log(storedValue); 
    } catch (error) {
      Alert.alert("Error", "There was an error.");
    }
  }
  _onLogout = () => {
    AsyncStorage.removeItem("@myApp:username").then(
      this.props.navigation.navigate("Login")
    );
  };
  render() {
    return (
      <View style={styles.container}>
        <ImageBackground
          source={require("./assets/bg1.jpg")}
          style={{
            flex: 1,
            width: "100%",
            height: "100%"
          }}
        >
          <View
            style={{
              backgroundColor: "rgba(0,0,0,0)",
              flex: 1,
              justifyContent: "center"
            }}
          >
            <Text
              style={{
                alignSelf: "center",
                backgroundColor: "#000fff",
                padding: 10,
                color: "#fff"
              }}
            >
              {`Hello, ${this.state.name} `}
            </Text>
            <TouchableOpacity
              style={{
                margin: 20,
                padding: 10,
                width: "50%",
                backgroundColor: "#1a73e8",
                justifyContent: "center",
                alignSelf: "center"
              }}
              onPress={this._onLogout}
            >
              <Text
                style={{ color: "#FFF", textAlign: "center", fontSize: 18 }}
              >
                Log out?
              </Text>
            </TouchableOpacity>
          </View>
        </ImageBackground>
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

您可以创建一个包含常量的js文件。 然后可以在Constant.js文件中添加如下所示的密钥:

 export const userNameKey= '@myApp:username';

,您可以在屏幕上访问该键,如下所示:

import { userNameKey} from './Constants';

并将其用作:

const login = AsyncStorage.getItem(userNameKey);