导航仪和AsyncStorage反应原生

时间:2016-07-14 06:07:08

标签: javascript ios react-native asyncstorage

您好我是本地新人,现在了解AsyncStorage。

我想实现条件渲染导航器。如果AsyncStorage中有值键,则初始路由转到Page2,如果AsyncStorage中没有值键,则初始路由转到Page1。

如果我关闭应用程序并再次重新打开,我希望它向我显示相应的页面是否有密钥。请帮忙。

这是我到目前为止所做的事情:



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;
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

你可以在TestAsync类中执行类似的操作

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

对于'无法读取属性推送未定义'错误

在render方法的page2代码中,您需要传递导航器的引用

而不是

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

使用此

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

答案 1 :(得分:1)

如果有人使用React Navigation version 5

检查以下代码。可能有帮助

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>
  );
}