【问题标题】:Implementing promises and AsyncStorage in react-native在 react-native 中实现 Promise 和 AsyncStorage
【发布时间】:2015-12-04 17:53:46
【问题描述】:

我有什么

2 个功能-

  1. getListInfo - 这里我检查一个对象是否存在,如果不存在,创建它,然后返回它。

  2. getInitialState - react native 的默认函数。

我想要达到的目标

尝试从 getInitialState 调用 getListInfo,并最终填充 listview。

但是,发生了什么-

甚至在返回值 obj 之前,整个页面的代码就已被执行。所以,问题是,列表视图正在获取未定义的数据。

我所知道的

使用promise解决问题。但是,方法不对。

实际代码 -

getListInfo : function() {
    AsyncStorage.getItem('listobject').then((obj) => {
    if(obj == undefined)
    {
        var obj1 ={};
        obj1.data ={};
        obj1.data.isdirty = true;
        console.log("obj1 = "+ JSON.stringify(obj1));
        AsyncStorage.setItem('listobject',obj1);
        obj = AsyncStorage.getItem('listobject');
        console.log("obj = "+ JSON.stringify(obj));
    }
    if(obj.data.isdirty)
    {
        obj.data.isdirty = false;
        AsyncStorage.setItem('listobject',JSON.stringify(obj));
        return AsyncStorage.getItem('listobject');
    }
}).done();
},


  getInitialState: function() {
    applistglobal = this.checkLocalStore();

    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows(this._genRows({})),
    };
  },


render: function() {
    /* BLAH BLAH BLAH */
}

Promise 部分代码(getInitialState 函数)- 我使用了 Promise,但是,即使是函数调用也失败了。所以,请忽略这部分代码并评估上面的代码。

getInitialState: function() {
    var promise = new Promise(function (resolve, reject) {
      resolve(this.getListInfo());
    });

    promise.then((listobject) => {
      console.log("getInitialState listobject "+listobject);
    })

    promise.catch((error) => {
      console.log("ERROR"+error);
    })

    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows(this._genRows({})),
    };
  },

【问题讨论】:

    标签: javascript asynchronous reactjs promise react-native


    【解决方案1】:

    您设置它的方式不是通常的做法。即在 getInitialState 中发出请求。当 promise 完成时返回空状态和 setState。您可以在 componentWillMount 或 componentDidMount 中启动请求。请参阅 react-native 站点上的此示例 https://facebook.github.io/react-native/docs/asyncstorage.html。不过他们使用的是 ES7 异步结构。

    【讨论】:

    • 是的。现在我看到他们正在使用 ES7 异步结构。我正在检查一个较旧的 repo 克隆。谢谢。
    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多