我拥有的
2个功能-
getListInfo – 这里我检查一个对象是否存在,如果不存在,创建它,然后返回它。
getInitialState – react native 的默认函数。
我想要达到的目标
尝试从 getInitialState 调用 getListInfo,并最终填充列表视图。
但是,发生了什么——
甚至在返回值 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({})),
};
},
您设置它的方式不是通常的做法。即在 getInitialState 中发出请求。 当 promise 完成时返回空状态和 setState。 您可以在 componentWillMount 或 componentDidMount 中启动请求。 在 react-native 网站上 查看这个示例 https://www.chaindev.cn/34094474-implementing-promises-and-asyncstorage-in-react-native/。 他们虽然使用 ES7 异步结构。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70016198/viewspace-2885637/ ,如需转载,请注明出处,否则将追究法律责任。