我有的
2个功能
getListInfo-在这里,我正在检查对象是否存在,如果不存在,请创建它,然后将其返回。
getInitialState-react native的默认功能。
我想要达到的目标
尝试从getInitialState调用getListInfo,并最终填充listview。
但是,发生了什么事-
甚至在返回值obj之前,整个页面的代码都将被执行。因此,问题在于,列表视图正在获取未定义的数据。
我知道的
用承诺来解决问题。但是,不是正确的方法。
实际代码-
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函数)-我使用了promises,但是,即使函数调用也失败了。因此,请忽略代码的这一部分并评估上面的代码。
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中进行请求。承诺完成后,返回空状态和setState。您可以在componentWillMount或componentDidMount中启动请求。在react-native网站上查看此示例https://facebook.github.io/react-native/docs/asyncstorage.html。他们正在使用ES7异步构造。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句