在 react-native 中實現(xiàn) Promise 和 AsyncStorage

問題

2個功能-

getListInfo – 這里我檢查一個對象是否存在,如果不存在,創(chuàng)建它,然后返回它。

getInitialState – react native 的默認函數(shù)。

我想要達到的目標

嘗試從 getInitialState 調(diào)用 getListInfo,并最終填充列表視圖。

但是,發(fā)生了什么,甚至在返回值 obj 之前,整個頁面的代碼就已被執(zhí)行。所以,問題是,列表視圖正在獲取未定義的數(shù)據(jù)。

我知道的,使用promise來解決問題。但是,方法不對。

實際代碼 –

getListInfo :function() {AsyncStorage.getItem('listobject').then((obj) =>{if(obj ==undefined){varobj1 ={};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));returnAsyncStorage.getItem('listobject');}}).done();},getInitialState:function() {applistglobal =this.checkLocalStore();vards =newListView.DataSource({rowHasChanged:(r1, r2) =>r1 !== r2});return{dataSource: ds.cloneWithRows(this._genRows({})),};},render:function() {/* BLAH BLAH BLAH */}

Promise 部分代碼(getInitialState 函數(shù))- 我使用了 Promise,但是,即使函數(shù)調(diào)用也失敗了。所以,請忽略這部分代碼并評估上面的代碼。

getInitialState:function() {varpromise =newPromise(function(resolve, reject) {resolve(this.getListInfo());});promise.then((listobject) =>{console.log("getInitialState listobject "+listobject);})promise.catch((error) =>{console.log("ERROR"+error);})vards =newListView.DataSource({rowHasChanged:(r1, r2) =>r1 !== r2});return{dataSource: ds.cloneWithRows(this._genRows({})),};},


解決方案

您設置它的方式不是通常的做法。即在 getInitialState 中發(fā)出請求。當 promise 完成時返回空狀態(tài)和 setState。您可以在 componentWillMount 或 componentDidMount 中啟動請求。在 react-native 網(wǎng)站上查看這個示例https://facebook.github.io/react-native/docs/asyncstorage.html 。他們雖然使用 ES7 異步結構。

原文鏈接:在 react-native 中實現(xiàn) Promise 和 AsyncStorage

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容