【问题标题】:React Native - AsyncStorage returns me null if I try to get the stringReact Native - 如果我尝试获取字符串,AsyncStorage 将返回 null
【发布时间】:2017-07-21 18:10:50
【问题描述】:

我正在使用 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”,我不知道如何解决它。 提前感谢您的回答。

【问题讨论】:

  • 您将无法通过这种方式导入文件:require("../JsonLists/"+this.state.promessa)。您不能动态导入文件。查看this answer 了解原因。
  • 谢谢,我修复了 Antoine Grandchamp 所说的 require 错误。然后我修复了 dataObject 问题,如您所说,将其放入 then 链中,谢谢。

标签: javascript react-native null setstate asyncstorage


【解决方案1】:

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

试试:

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

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

这应该会提醒您的数据。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:
        async myMethode() {
        AsyncStorage.getItem("").then((value)=>alert(value));
        

        }

        像这样尝试。在需要的地方调用方法

        【讨论】:

        • async 关键字将帮助您异步获取数据
        【解决方案5】:

        使用异步/等待。

        async componentDidMount () {
        
        
            try {
        
                const item = await this.someMethodAsync();
        
            } catch (e) {
        
               console.log("Error getting item", e);
            }
        }    
        
        async someMethodAsync () {
             try {
        
                  let item = AsyncStorage.getItem("foo");
                  console.log(item);
             catch (e) {
                  throw e;
             }
        
             return item; // Could be any value, including null.
        }
        

        【讨论】:

          猜你喜欢
          • 2021-08-27
          • 2017-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-25
          • 2019-01-12
          • 2016-09-16
          相关资源
          最近更新 更多