AsyncStorage返回null [react-native]

时间:2018-12-29 06:55:07

标签: react-native react-navigation asyncstorage

我有一个createSwitchNavigator,其中有3条路由,其InitialRouteName为AuthLoading

App.js

import AuthLoadingScreen from './screens/AuthLoadingScreen';
import {
  createDrawerNavigator,
  createBottomTabNavigator,
  DrawerItems,
  createSwitchNavigator,
  createStackNavigator
} from "react-navigation";
import AuthScreen from "./screens/AuthScreen";
import ProductsScreen from "./screens/ProductsScreen";
import AuthLoadingScreen from "./screens/AuthLoadingScreen";
import ForgetPasswordScreen from "./screens/ForgetPasswordScreen";
import ProductsDemo from "./screens/ProductsDemo";
import RegisterScreen from "./screens/RegisterScreen";

const AppNavigator = () => {
  return <MainNavigation />;
};

const AppBottomTabNavigator = createBottomTabNavigator(
  {
    home: ProductsScreen
  }
);

const MainNavigation = createDrawerNavigator(
  {
    Home: AppBottomTabNavigator,
  },
  {
    drawerWidth: width - width / 4,
    drawerPosition: "left",
    drawerOpenRoute: "DrawerOpen",
    drawerCloseRoute: "DrawerClose",
    drawerToggleRoute: "DrawerToggle",
    drawerBackgroundColor: "#fff",
    initialRouteName: "Home"
  }
);


const AuthDrawerNavigator = createDrawerNavigator(
  {
    Products: createStackNavigator(
      {
        SignIn: AuthScreen,
        ForgetPwd: ForgetPasswordScreen,
        SignUp: RegisterScreen,
        Product: ProductsDemo
      },
      {
        initialRouteName: "Product",
        navigationOptions: {
          header: null
        }
      }
   )
 },
 {
   drawerWidth: width - width / 4,
   drawerPosition: "left"
 }
);

class App extends Component {
  componentDidMount() {
    SplashScreen.hide();
    navigatorRef = this.navigator;
  }
  render() {
    const Main = createSwitchNavigator({
      AuthLoading: AuthLoadingScreen,
      Auth: AuthDrawerNavigator,
      App: AppNavigator
    });
    return (
      <StoreProvider store={store}>
        <PaperProvider theme={theme}>
          <Main />
        </PaperProvider>
      </StoreProvider>
    );
  }
}


export default App;

AuthLoadingScreen仅检查...如果应用程序具有令牌,则将用户登录到AuthDrawerNavigator的其他路由中,则AuthDrawerNavigator具有注册和登录页面。

AuthLoadingScreen.js

import React, { Component } from "react";
import { View, ActivityIndicator, AsyncStorage, StatusBar } from 
"react-native";

class AuthLoadingScreen extends Component {

    constructor() {
        super()
        this.loadApp()
    }

    loadApp = async () => {
        const userToken = await AsyncStorage.getItem('userToken');

        this.props.navigation.navigate(userToken? 'App' : 'Auth');
    }

  render() {
    return (
      <View
        style={{
          justifyContent: "center",
          alignItems: "center",
          flex: 1,
          backgroundColor: "#fff"
        }}
      >
        <StatusBar translucent={false} backgroundColor="#007aff" />
        <ActivityIndicator size="large" color="#007aff" />
      </View>
    );
  }
}
export default AuthLoadingScreen;

在我的RegisterScreen中,随着用户在后端注册,我将使用AsyncStorage在本地存储其详细信息...

const registerUser = async (first_name, last_name, email, pwd_1, phone, dispatch) => {
axios.post(`${ROOT_URL}registerUser`, {
    phone: `+91${phone}`,
    first_name: `${first_name}`,
    last_name: `${last_name}`,
    email: `${email}`,
    pwd: `${pwd_1}`
})
.catch(err => dispatch({
    type: REQ_FAIL,
    val: err.message
}))
dispatch({
    type: REQ_SUCCESS
})
await AsyncStorage.setItem('f_name', first_name);
await AsyncStorage.setItem('l_name', last_name);
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);

}

现在,随着用户的注册,我将其详细信息存储在本地,并且在注册后将其路由到loginScreen,并且在登录后,我可以在homeScreen中查看详细信息

ProductsScreen.js

import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  StatusBar,
  Image,
  TextInput,
  AsyncStorage,
} from "react-native";
import { Appbar } from "react-native-paper";
import { Icon } from "react-native-elements";

class ProductsScreen extends Component {
  state = {
    first_name: "",
    last_name: "",
    phone: "",
    email: ""
  };

  async componentWillMount() {
    let f_name = await AsyncStorage.getItem("f_name");
    let l_name = await AsyncStorage.getItem("l_name");
    let phone = await AsyncStorage.getItem("phone");
    let email = await AsyncStorage.getItem("email");
    this.setState({
      first_name: f_name,
      last_name: l_name,
      phone: phone,
      email: email
    });
  }


render() {
  const { navigation } = this.props;
  return (
      <View style={{ flex: 1, backgroundColor: "#fff" }}>

        <View style={{ flex: 1 }}>
          <View
            style={{
              backgroundColor: "#fff",
              borderRadius: 12,
              flexDirection: "row",
              justifyContent: "space-around",
              alignItems: "center",
              marginHorizontal: 12,
              marginVertical: 5,
              elevation: 1,
              zIndex: 9
            }}
          >
            <Image
              style={{
                height: 50,
                width: 50,
                marginVertical: 8
              }}
              alignSelf="center"
              resizeMode="contain"
              source={require("../components/Images/avatar.png")}
            />
            <View style={{ justifyContent: "space-around" }}>
              <Text>{`${this.state.first_name} ${
                this.state.last_name
              }`}</Text>
              <Text>{this.state.phone}</Text>
              <Text>{this.state.email}</Text>
            </View>
          </View>
        </View>
      </View>
    );
  }
}
export default ProductsScreen;

但是下一次由于用户已经注册,用户将直接路由到loginScreen,并且在登录后,这次AsyncStorage返回null

尽管从asyncStorage检索值的代码与上面相同:

  async componentWillMount() {
let f_name = await AsyncStorage.getItem("f_name");
let l_name = await AsyncStorage.getItem("l_name");
let phone = await AsyncStorage.getItem("phone");
let email = await AsyncStorage.getItem("email");
this.setState({
  first_name: f_name,
  last_name: l_name,
  phone: phone,
  email: email
});

}

0 个答案:

没有答案