从react-native中的AsyncStorage获取项目值

6 react-native

我是初学者,仍在尝试学习本机反应,所以请帮助我!

我想在函数外部访问 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})
Run Code Online (Sandbox Code Playgroud)

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

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

错误

找不到变量 abc

问题

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

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

感谢您贡献宝贵的时间

Ray*_*aba 6

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>
    );
}
Run Code Online (Sandbox Code Playgroud)

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