当我尝试在React Native中使用AsyncStorage保存值时,但是当我尝试检索值时,我有{“ _U”:0,“ _V”:0,“ _W”:null,“ _X”:null}

问题描述

我的按钮的代码是:

<Button style={styles.shopButtonStyle} onPress={async () => { await this.setState({'selectedShop': negozio['@id'] }); await AsyncStorage.setItem('@shop',"test"); }}>
          <Text>Scegli</Text>
        </Button>

然后我转到另一页:

<Button style={styles.shopButtonStyle} onPress={async () => { this.props.navigation.navigate('Bookingstep2');  
        }}>
          <Text>Continua</Text>
        </Button>

在新页面中,我有

componentDidMount(){
async () => { const shop = await AsyncStorage.getItem('@shop'); console.log(shop);  }

}

但是控制台为空。谁能帮我吗?

解决方法

您应该改为让componentDidMount异步,并使用try catch来检查以下错误:

async componentDidMount() {
try {
   const shop = await AsyncStorage.getItem('@shop');
   console.log(shop);
   } catch (error) {
    console.log(error); 
   }
}

可能有任何错误,因此您可以在catch块中检查错误