首页 > 解决方案 > 从 react-native 中的 AsyncStorage 获取项目值

问题描述

我是一个初学者,仍然尝试学习反应原生所以帮助我!

我想在函数外访问 AsyncStorage.getItem 值。我将通过代码进一步解释

这是我的代码

import {AsyncStorage} from 'react-native';

在 screen1 上设置该值

AsyncStorage.setItem('mobileno', JSON.stringify(MobileNo));

尝试在屏幕 2 上获取该值

 AsyncStorage.getItem('mobileno', (err, MobileNumber) => {
    let abc = MobileNumber;
    console.log("abc value " + abc)
   })


  let { MobileNo } = abc;
  console.log({MobileNo})

我想在函数外部访问该 abc 值,let { MobileNo } = abc;但它显示错误!

注意: [console.log("abc value " + abc)完美工作]

错误

找不到变量 abc

问题

那么,我怎样才能访问整个页面的那个 abc 或那个 AsyncStorage 值[在那个函数之外];因为我也想在其他功能中使用该值!

简而言之,我希望 AsyncStorage 中的存储值在其他功能中使用。

感谢您贡献宝贵的时间

标签: react-native

解决方案


constructor(props) {
    super(props);
    this.state = {
        mobileNumber: '',
    };
}

componentDidMount() {
    AsyncStorage.getItem('mobileno').then((mobileNo) => {
        if(mobileNo){
            this.setState({mobileNumber: mobileNo});
            console.log(this.state.mobileNumber);
        }
    });
}

render() {
    return(
        <View>
            <Text>{this.state.mobileNumber}</Text>
        </View>
    );
}

在这种情况下 async/await 不是必需的,因为.then()仅在getItem()函数完成获取项目后调用。


推荐阅读