在 react-native 中實現 Promise 和 AsyncStorage
問題
我擁有的
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部落格 ” ,連結:http://blog.itpub.net/70016198/viewspace-2885637/,如需轉載,請註明出處,否則將追究法律責任。