如何在不重新加载整个应用程序的情况下获取异步数据

时间:2019-02-19 10:54:46

标签: javascript reactjs react-native

我正在尝试在用户单击bottomTabNavigator时重新加载组件屏幕。我的意思是在我的第一个组件屏幕“ AnotherA.js”中,我正在使用textinput将用户输入的数据存储在异步存储中,而在另一个组件“ AnotherB.js”中,我正在使用异步存储的get()将我存储的数据显示在屏幕。我可以在重新加载整个应用程序时第一次看到存储的数据。

我试图通过不立即加载整个应用程序来获取数据,方法是使用bottomTabNavigator导航并立即显示。

//App.js

import React, { Component } from "react";
import { createAppContainer } from 'react-navigation';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';
import { TabNavigator } from 'react-navigation';
import AnotherA from './AnotherA';
import AnotherB from './AnotherB';

const AppNavigator = createMaterialBottomTabNavigator(
  {
    AnotherA: { screen: AnotherA },
    AnotherB: { screen: AnotherB }
  },
  {
    initialRouteName: 'AnotherA',
    activeColor: '#f0edf6',
    inactiveColor: '#3e2465',
    barStyle: { backgroundColor: '#694fad' },
    pressColor: 'pink',
  },
  {
    //tabBarComponent: createMaterialBottomTabNavigator /* or TabBarTop */,
    tabBarPosition: 'bottom',
    defaultnavigationOptions: ({ navigation }) => ({
      tabBarOnPress: (scene, jumpToIndex) => {
        console.log('onPress:', scene.route);
        jumpToIndex(scene.index);

      },
    }),

  }
);
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;

// AnotherA.js

import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';

export default class AnotherA extends Component {
    constructor(props) {
        super(props);
        this.state = {
            myKey: '',
            text1: '',

        }
    }

    async getKey() {
        try {
            //const value = await AsyncStorage.getItem('@MySuperStore:key');
            const key = await AsyncStorage.getItem('@MySuperStore:key');

            this.setState({
                myKey: key,
            });
        } catch (error) {
            console.log("Error retrieving data" + error);
        }
    }

    async saveKey(text1) {
        try {
            await AsyncStorage.setItem('@MySuperStore:key', text1);
        } catch (error) {
            console.log("Error saving data" + error);
        }
    }

    async resetKey() {
        try {
            await AsyncStorage.removeItem('@MySuperStore:key');
            const value = await AsyncStorage.getItem('@MySuperStore:key');
            this.setState({
                myKey: value,
            });
        } catch (error) {
            console.log("Error resetting data" + error);
        }
    }

    componentDidMount() {
        this.getKey();
    }

    render() {
        return (
            <View style={styles.container}>
                <TextInput
                    placeholder="Enter Data"
                    value={this.state.myKey}
                    onChangeText={(value) => this.setState({ text1: value })}
                    multiline={true}
                />
                <Button
                    onPress={() => this.saveKey(this.state.text1)}
                    title="Save"
                />
                <Button
                    //style={styles.formButton}
                    onPress={this.resetKey.bind(this)}
                    title="Reset"
                    color="#f44336"
                    accessibilityLabel="Reset"
                />
                </View>
        )
    }
}

// AnotherB.js

import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';

export default class AnotherB extends Component {
    constructor(props) {
        super(props);
        this.state = {
            myKey: '',
            text1: '',

        }
    }

    async getKey() {
        try {
            //const value = await AsyncStorage.getItem('@MySuperStore:key');
            const key = await AsyncStorage.getItem('@MySuperStore:key');

            this.setState({
                myKey: key,
            });
        } catch (error) {
            console.log("Error retrieving data" + error);
        }
    }

    componentDidMount() {
        this.getKey();
    }

    render() {
        //const { navigate } = this.props.navigation;
        //const { newValue, height } = this.state;
        return (
            <View style={styles.container}>
                <Text>{this.state.myKey}</Text>
            </View>
        )
    }
}

请建议,我是React-Native的新手。

2 个答案:

答案 0 :(得分:1)

问题在于,安装组件时,您正在从AsyncStorage中检索值。不幸的是,切换标签时,这并不会在屏幕上加载该值。您需要做的是updates订阅导航生命周期。

这很简单。您可以订阅四个生命周期事件。您可以选择要订阅的对象。

  
      
  • willFocus-屏幕将聚焦
  •   
  • didFocus-屏幕聚焦(如果存在过渡,则过渡完成)
  •   
  • willBlur-屏幕将无法对焦
  •   
  • didBlur-屏幕未聚焦(如果存在过渡,则过渡完成)
  •   

您在组件装入时订阅事件,然后在卸载时取消订阅。因此,当您订阅的事件发生时,它将调用您已放入订阅者回调中的函数。

因此您可以在自己的AnotherB.js中做类似的事情:

componentDidMount() {
    // subscribe to the event that we want, in this case 'willFocus'
    // when the screen is about to focus it will call this.getKey
    this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.getKey);
}

componentWillUnmount() {
    // unsubscribe to the event 
    this.willFocusSubscription.remove();
}

getKey = async () => { // update this to an arrow function so that we can still access this, otherwise we'll get an error trying to setState.
    try {
        const key = await AsyncStorage.getItem('@MySuperStore:key');
        this.setState({
            myKey: key,
        });
    } catch (error) {
        console.log("Error retrieving data" + error);
    }
}

这是我制作的一种速食小吃,显示它可以正常工作,https://snack.expo.io/@andypandy/navigation-life-cycle-with-asyncstorage

答案 1 :(得分:0)

您可以尝试在getItem之后添加

AsyncStorage.getItem("@MySuperStore:key").then((value) => {
    this.setState({
        myKey: value,
    });
})
.then(res => {
    //do something else
});