AsyncStorage获取项目

时间:2017-10-26 02:44:22

标签: javascript react-native

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

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 */     }

3 个答案:

答案 0 :(得分:2)

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

componentDidMount(){
    AsyncStorage.getItem('customer_id', (error,value) => {
        if (!error) { //If there are no errors
            //handle result
            if (result !== null) this.setState({customer_id:value}); 
        }
    });
}

答案 1 :(得分:1)

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

For more information you can visit official docs.

答案 2 :(得分:0)

这里是我的回答,修改了Ryan的回答

&#13;
&#13;
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
}));
&#13;
&#13;
&#13;