首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsyncStorage获取项

AsyncStorage获取项
EN

Stack Overflow用户
提问于 2017-10-26 02:44:21
回答 3查看 2.1K关注 0票数 2

如何在“AsyncStorage”中获取componentDidMount项,这是我的代码

代码语言:javascript
复制
componentDidMount() {

	AsyncStorage.getItem('customer_id').then((value)=> this.setState({ customer_id: value }));
        console.log(this.state.customer_id); /* doesn't work */
        console.log(`${this.state.customer_id}`); /* doesn't work */
  }
	
	
  render() {return <View><Text>Customer ID : {this.state.customer_id}</Text></View>; /* it's work */     }

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-10-26 03:15:32

你必须处理AsyncStorage -异步的,有趣的!无论如何,您希望将一个回调传递给处理结果的getItem方法。试一试

代码语言:javascript
复制
componentDidMount(){
    AsyncStorage.getItem('customer_id', (error,value) => {
        if (!error) { //If there are no errors
            //handle result
            if (result !== null) this.setState({customer_id:value}); 
        }
    });
}
票数 3
EN

Stack Overflow用户

发布于 2017-10-26 02:53:02

代码语言:javascript
复制
try {
   const value = await AsyncStorage.getItem('@MySuperStore:key');
     if (value !== null){
    // We have data!!
    console.log(value);
  }
} catch (error) {
  // Error retrieving data
}

要了解更多信息,您可以访问官方文档。

票数 1
EN

Stack Overflow用户

发布于 2017-10-27 03:39:42

这是我的答案,来自赖安的回答。

代码语言:javascript
复制
var cust_id_tmp = '';

AsyncStorage.getItem('customer_id', function(errs, result) {
  if (!errs) {
    if (result !== null) {
      //this.setState({customer_id:result}); <= we can't do this
      cust_id_tmp = result;
      console.log('customer_id : ' + result); /* it works */

    }
  }
}).then((value) => this.setState({
  cust_id: cust_id_tmp
}));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46945039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档