React Native AsyncStorage无法获取数据

时间:2017-12-07 08:10:21

标签: android react-native asyncstorage

我使用以下代码存储和检索数据。但它并没有按照我的意愿运作。

设置数据:

async setDataFromApi(token, json) {
const {goBack} = this.props.navigation; // Navigation
let iext_inf = {
  token: token,
  userid: json.data.id,
  username: json.data.username,
  image: json.data.profile_picture,
};
console.log(iext_inf);
try {
  await AsyncStorage.setItem('iext_inf', JSON.stringify(iext_inf) ); // Stuck here
  goBack();
} catch (error) {
  console.log("Error");
}
}

获取数据

async componentWillMount() {
    try {
      const value = await AsyncStorage.getItem("iext_inf"); //Stuck here
console.log(value);

  if (value !== null){
    this.setState({
      data : value
    })
  }

  if ( this.state.data !== null ) {
    this.props.navigation.navigate('Home', {'access_token': value});
  }

} catch (error) {
  console.log(error);
}
}

我做错了什么?我尝试添加单个数据并检索它,并且由于某种原因它起作用。现在不是。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

  

AsyncStorage仅将字符串作为值和键。

您正在传递对象尝试将字符串设置为对象。我不确定JSON.stringfy()适用于AsyncStorage