React Native - 如果我尝试获取字符串,AsyncStorage会返回null

问题描述 投票:0回答:4

我正在使用AsyncStorage,我需要将值存储到“facoltà”并将其保存到调用this.setState的“promessa”中。我写了那段代码:

constructor(props){
  super(props)
  AsyncStorage.setItem("facoltà","PROFS.json")
}
componentWillMount(){
  AsyncStorage.getItem("facoltà").then((value)=>
  { 
    console.log(value); // the console returns me PROFS.json so I thought it was working
    this.setState({promessa:value})
  }):
  var dataObjects=require("../JsonLists/"+this.state.promessa) // but here this.state.promessa returns me null
 }

问题是this.state.promessa返回“null”而不是“PROFS.json”,我无法弄清楚如何解决它。提前感谢您的回答。

javascript react-native null setstate asyncstorage
4个回答
2
投票

ComponentWillMount将不会在构造函数中的setItem Promise之后完成getItem Promise。

尝试:

componentWillMount(){
 AsyncStorage.setItem("facoltà",PROFS.json)
}

render(){
...
  AsyncStorage.getItem("facoltà").then((value)=>alert(value));
...
}

这应该提醒您的数据。


0
投票

AsyncStorage.getItem返回一个promise,因此将在then的回调中解析。这意味着您的下一行var dataObjects=require("../JsonLists/"+this.state.promessa)在承诺解决之前执行。

如果您需要在then方法中立即使用dataObjects,则应将该行放在componentWillMount回调中并具有默认初始值。


0
投票

我认为这是一个时间问题。你正在使用.then的一个promise,它在var dataObjects试图要求它之后设置状态。

您是否尝试将var dataObjects放在.then代码中?


0
投票
async myMethode() {
AsyncStorage.getItem("").then((value)=>alert(value));

}

尝试这样。调用所需的方法

© www.soinside.com 2019 - 2024. All rights reserved.