简体   繁体   中英

Navigator & AsyncStorage react native

Hello i'm new in react native and currently learn about AsyncStorage.

I want to implement conditional to render navigator. If there's value key in AsyncStorage, the initial route go to Page2 and if there's no value key in AsyncStorage, the initial route go to Page1.

If i close the app and re-open again, I want it shows me the corresponding page whether there is a key. please help.

Here's what i've done so far:

 import React, { Component } from 'react'; import { AppRegistry, TextInput, StyleSheet, Text, View, Navigator, TouchableOpacity, AsyncStorage, } from 'react-native'; var initialRoute = {id: 1} var STORAGE_KEY = '@AsyncStorageExample:key'; var SCREEN_WIDTH = require('Dimensions').get('window').width; var BaseConfig = Navigator.SceneConfigs.FloatFromRight; var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, { snapVelocity: 8, edgeHitWidth: SCREEN_WIDTH, }); var CustomSceneConfig = Object.assign({}, BaseConfig, { springTension: 100, springFriction: 1, gestures: { pop: CustomLeftToRightGesture, } }); var Page1 = React.createClass({ _goToPage2() { AsyncStorage.setItem(STORAGE_KEY, "this is the key"); this.props.navigator.push({id: 2}) }, render() { return ( <View style={[styles.container, {backgroundColor: 'white'}]}> <Text style={styles.welcome}> This is Page 1 </Text> <TouchableOpacity onPress={this._goToPage2}> <View style={{paddingVertical: 2, paddingHorizontal: 7, backgroundColor: 'black'}}> <Text style={styles.buttonText}>Save Key</Text> </View> </TouchableOpacity> </View> ) }, }); var Page2 = React.createClass({ componentDidMount() { this._loadInitialState(); }, async _loadInitialState() { try { var value = await AsyncStorage.getItem(STORAGE_KEY); if (value !== null){ this.setState({selectedValue: value}) } else { } } catch (error) { } }, getInitialState() { return { selectedValue: null }; }, _signOutPressed(){ AsyncStorage.removeItem(STORAGE_KEY); this.props.navigator.push({id: 1}) }, render() { if(this.state.selectedValue === null) { begin = <Page1 /> } else{ begin = <View style={[styles.container, {backgroundColor: 'white'}]}> <Text style={styles.welcome}>This is Page 2</Text> <Text>KEY: {this.state.selectedValue}</Text> <TouchableOpacity onPress={this._signOutPressed}> <View style={{paddingVertical: 2, paddingHorizontal: 7, margin: 10, backgroundColor: 'black'}}> <Text style={styles.buttonText}>Delete Key</Text> </View> </TouchableOpacity> </View> } return ( begin ); }, }); var TestAsync = React.createClass({ _renderScene(route, navigator) { if (route.id === 1) { return <Page1 navigator={navigator} /> } else if (route.id === 2) { return <Page2 navigator={navigator} /> } }, _renderScene1(route, navigator) { if (route.id === 1) { return <Page1 navigator={navigator} /> } else if (route.id === 2) { return <Page2 navigator={navigator} /> } }, _configureScene(route) { return CustomSceneConfig; }, render() { var initialRoute = {id:1} if(AsyncStorage.getItem(STORAGE_KEY) != null){ initialRoute = {id:2} } return( <Navigator initialRoute={initialRoute} renderScene={this._renderScene} configureScene={this._configureScene} /> ); } }); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, color: 'black', }, buttonText: { fontSize: 14, textAlign: 'center', margin: 10, color: 'white', }, default: { height: 26, borderWidth: 0.5, fontSize: 13, padding: 4, marginHorizontal:30, marginBottom:10, }, }); module.exports = TestAsync;

You can do something like this, In TestAsync class

render() {
    var initialRoute = {id:1}
    if(AsyncStorage.getItem(STORAGE_KEY) != null){
       initialRoute = {id:2}
    }
    return(
       <Navigator
        initialRoute={initialRoute}
        renderScene={this._renderScene}
        configureScene={this._configureScene} />
    );
}

For 'Cannot read property push of undefined' error

In your page2 code in render method you need to pass reference of navigator

Instead of

 if(this.state.selectedValue === null) {
      begin = <Page1} />
 }

use this

 if(this.state.selectedValue === null) {
      begin = <Page1 navigator={this.props.navigator} />
 }

If Anyone use React Navigation version 5 then,

Check the following code. It may help

function MyStack() {
  const [isLogedin, setIsLogedin] = React.useState(false);

  AsyncStorage.getItem('isLogedin').then((data) =>{
    if(data != null && data == true) setIsLogedin(true)
    else setIsLogedin(false)
  })

  return (
    <Stack.Navigator headerMode={"none"}>
      {isLogedin ? <Stack.Screen name="Home" component={AppTabs} /> : <Stack.Screen name="AuthNav" component={AuthNav} />}
    </Stack.Navigator>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM