Przeglądaj źródła

'封装fetch,增加react-native-storage组件'

Rorschach 5 lat temu
rodzic
commit
f608620eb8
8 zmienionych plików z 259 dodań i 30 usunięć
  1. 10 21
      App.js
  2. 17 1
      README.md
  3. 138 0
      package-lock.json
  4. 1 0
      package.json
  5. 7 4
      pages/components/MainPage.js
  6. 6 4
      pages/services/library.js
  7. 6 0
      pages/utils/efunRequest.js
  8. 74 0
      pages/utils/request.js

+ 10 - 21
App.js

@@ -8,16 +8,10 @@
 
 import React, { Component } from "react";
 import {
-  Platform,
-  StyleSheet,
-  Text,
-  View,
-  Button,
-  ImageBackground,
-  Image,
-  DeviceEventEmitter
+  AsyncStorage 
 } from "react-native";
 import { createStackNavigator, createAppContainer } from "react-navigation";
+import Storage from 'react-native-storage';
 import MainActivity from "./pages/MainActivity";
 import SchoolAge from "./pages/components/SchoolAge";
 import MainPage from "./pages/components/MainPage";
@@ -54,16 +48,11 @@ const RootNavigator = createStackNavigator(
 const App = createAppContainer(RootNavigator);
 export default App;
 
-// type Props = {};
-// export default class App extends Component<Props> {
-//   render() {
-//     return (
-//       <View>
-//         <ImageBackground
-//           source={require("../imgs/splash.jpg")}
-//           style={{ flex: 1, width: "100%", height: "100%" }}
-//         />
-//       </View>
-//     );
-//   }
-// }
+let storage = new Storage({
+  size: 1000,
+  storageBackend: AsyncStorage,
+  defaultExpires: null,
+  enableCache: true,
+})
+
+global.storage = storage

+ 17 - 1
README.md

@@ -19,4 +19,20 @@
 
 
 ## 已发现问题
-1. 首页搜索框,安卓手机每次输入内容后,键盘会消失,(受 `this.setData` 影响 )
+1. 首页搜索框,安卓手机每次输入内容后,键盘会消失,(受 `this.setData` 影响 )
+
+## storage 使用
+``` // 存储数据
+ global.storage.save({
+                    key:'token',
+                    data: data.access_token,
+                    expires: null
+                });
+```
+
+``` // 读取数据
+global.storage.load({
+        key:'token'
+    })
+```
+https://www.jianshu.com/p/72c3d3af094f

+ 138 - 0
package-lock.json

@@ -1451,6 +1451,23 @@
       "resolved": "https://registry.npm.taobao.org/babel-plugin-syntax-trailing-function-commas/download/babel-plugin-syntax-trailing-function-commas-7.0.0-beta.0.tgz",
       "integrity": "sha1-qiE8FDXiv/62/KhCKH71NK0F1c8="
     },
+    "babel-polyfill": {
+      "version": "6.23.0",
+      "resolved": "https://registry.npm.taobao.org/babel-polyfill/download/babel-polyfill-6.23.0.tgz",
+      "integrity": "sha1-g2TKYt+Or7gwSZ9pkXdGbDsDSZ0=",
+      "requires": {
+        "babel-runtime": "^6.22.0",
+        "core-js": "^2.4.0",
+        "regenerator-runtime": "^0.10.0"
+      },
+      "dependencies": {
+        "regenerator-runtime": {
+          "version": "0.10.5",
+          "resolved": "https://registry.npm.taobao.org/regenerator-runtime/download/regenerator-runtime-0.10.5.tgz",
+          "integrity": "sha1-M2w+/BIgrc7dosn6tntaeVWjNlg="
+        }
+      }
+    },
     "babel-preset-fbjs": {
       "version": "3.2.0",
       "resolved": "https://registry.npm.taobao.org/babel-preset-fbjs/download/babel-preset-fbjs-3.2.0.tgz",
@@ -1495,6 +1512,15 @@
         "babel-plugin-jest-hoist": "^24.6.0"
       }
     },
+    "babel-runtime": {
+      "version": "6.26.0",
+      "resolved": "https://registry.npm.taobao.org/babel-runtime/download/babel-runtime-6.26.0.tgz",
+      "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=",
+      "requires": {
+        "core-js": "^2.4.0",
+        "regenerator-runtime": "^0.11.0"
+      }
+    },
     "balanced-match": {
       "version": "1.0.0",
       "resolved": "http://registry.npm.taobao.org/balanced-match/download/balanced-match-1.0.0.tgz",
@@ -6248,6 +6274,91 @@
         "mimic-fn": "^1.0.0"
       }
     },
+    "opencollective": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npm.taobao.org/opencollective/download/opencollective-1.0.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fopencollective%2Fdownload%2Fopencollective-1.0.3.tgz",
+      "integrity": "sha1-ruY3K8KBRFg2kMPKja7PwSDdDvE=",
+      "requires": {
+        "babel-polyfill": "6.23.0",
+        "chalk": "1.1.3",
+        "inquirer": "3.0.6",
+        "minimist": "1.2.0",
+        "node-fetch": "1.6.3",
+        "opn": "4.0.2"
+      },
+      "dependencies": {
+        "ansi-escapes": {
+          "version": "1.4.0",
+          "resolved": "https://registry.npm.taobao.org/ansi-escapes/download/ansi-escapes-1.4.0.tgz",
+          "integrity": "sha1-06ioOzGapneTZisT52HHkRQiMG4="
+        },
+        "ansi-styles": {
+          "version": "2.2.1",
+          "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-2.2.1.tgz",
+          "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4="
+        },
+        "chalk": {
+          "version": "1.1.3",
+          "resolved": "https://registry.npm.taobao.org/chalk/download/chalk-1.1.3.tgz",
+          "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
+          "requires": {
+            "ansi-styles": "^2.2.1",
+            "escape-string-regexp": "^1.0.2",
+            "has-ansi": "^2.0.0",
+            "strip-ansi": "^3.0.0",
+            "supports-color": "^2.0.0"
+          }
+        },
+        "inquirer": {
+          "version": "3.0.6",
+          "resolved": "https://registry.npm.taobao.org/inquirer/download/inquirer-3.0.6.tgz",
+          "integrity": "sha1-4EqqnQW3o8ubD0B9BDdfBEcZA0c=",
+          "requires": {
+            "ansi-escapes": "^1.1.0",
+            "chalk": "^1.0.0",
+            "cli-cursor": "^2.1.0",
+            "cli-width": "^2.0.0",
+            "external-editor": "^2.0.1",
+            "figures": "^2.0.0",
+            "lodash": "^4.3.0",
+            "mute-stream": "0.0.7",
+            "run-async": "^2.2.0",
+            "rx": "^4.1.0",
+            "string-width": "^2.0.0",
+            "strip-ansi": "^3.0.0",
+            "through": "^2.3.6"
+          }
+        },
+        "node-fetch": {
+          "version": "1.6.3",
+          "resolved": "https://registry.npm.taobao.org/node-fetch/download/node-fetch-1.6.3.tgz",
+          "integrity": "sha1-3CNO3WSJmC1Y6PDbT2lQKavNjAQ=",
+          "requires": {
+            "encoding": "^0.1.11",
+            "is-stream": "^1.0.1"
+          }
+        },
+        "opn": {
+          "version": "4.0.2",
+          "resolved": "https://registry.npm.taobao.org/opn/download/opn-4.0.2.tgz",
+          "integrity": "sha1-erwi5kTf9jsKltWrfyeQwPAavJU=",
+          "requires": {
+            "object-assign": "^4.0.1",
+            "pinkie-promise": "^2.0.0"
+          }
+        },
+        "supports-color": {
+          "version": "2.0.0",
+          "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-2.0.0.tgz",
+          "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc="
+        }
+      }
+    },
+    "opencollective-postinstall": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npm.taobao.org/opencollective-postinstall/download/opencollective-postinstall-2.0.2.tgz",
+      "integrity": "sha1-Vlfxvt5ptuM6RZObBh61PTxsOok="
+    },
     "opn": {
       "version": "3.0.3",
       "resolved": "https://registry.npm.taobao.org/opn/download/opn-3.0.3.tgz",
@@ -6468,6 +6579,19 @@
       "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=",
       "dev": true
     },
+    "pinkie": {
+      "version": "2.0.4",
+      "resolved": "https://registry.npm.taobao.org/pinkie/download/pinkie-2.0.4.tgz",
+      "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA="
+    },
+    "pinkie-promise": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npm.taobao.org/pinkie-promise/download/pinkie-promise-2.0.1.tgz",
+      "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=",
+      "requires": {
+        "pinkie": "^2.0.0"
+      }
+    },
     "pirates": {
       "version": "4.0.1",
       "resolved": "https://registry.npm.taobao.org/pirates/download/pirates-4.0.1.tgz",
@@ -6976,6 +7100,15 @@
       "resolved": "https://registry.npm.taobao.org/react-native-screens/download/react-native-screens-1.0.0-alpha.22.tgz",
       "integrity": "sha1-ehIDd7Uqqbu5TQuFQaAUAmvpKJs="
     },
+    "react-native-storage": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npm.taobao.org/react-native-storage/download/react-native-storage-1.0.1.tgz",
+      "integrity": "sha1-LEk4df927DAZh8lRqDAvOlQ4EkE=",
+      "requires": {
+        "opencollective": "^1.0.3",
+        "opencollective-postinstall": "^2.0.2"
+      }
+    },
     "react-native-swiper": {
       "version": "1.5.14",
       "resolved": "https://registry.npm.taobao.org/react-native-swiper/download/react-native-swiper-1.5.14.tgz",
@@ -7421,6 +7554,11 @@
         "is-promise": "^2.1.0"
       }
     },
+    "rx": {
+      "version": "4.1.0",
+      "resolved": "https://registry.npm.taobao.org/rx/download/rx-4.1.0.tgz",
+      "integrity": "sha1-pfE/957zt0D+MKqAP7CfmIBdR4I="
+    },
     "rx-lite": {
       "version": "4.0.8",
       "resolved": "https://registry.npm.taobao.org/rx-lite/download/rx-lite-4.0.8.tgz",

+ 1 - 0
package.json

@@ -17,6 +17,7 @@
     "react-native-gesture-handler": "^1.1.0",
     "react-native-image-picker": "^0.28.1",
     "react-native-orientation": "^3.1.3",
+    "react-native-storage": "^1.0.1",
     "react-native-swiper": "^1.5.14",
     "react-native-video": "^4.4.1",
     "react-native-web": "^0.11.2",

+ 7 - 4
pages/components/MainPage.js

@@ -45,7 +45,12 @@ export default class MainPage extends BasePage {
   }
 
   updateRender(index) {
-    LibraryUrl.getIndex(index).success(res => {
+    // LibraryUrl.getIndex(index).success(res => {
+
+    // }).fail(() => {
+    //   alert(1111)
+    // })
+    LibraryUrl.getIndex(index).then((res) => {
       console.log(res)
       const monthTopicTitle = res.data.monthTopic.zone.title;
       const monthTopicScroll = res.data.monthTopic.zoneCourseVOList;
@@ -73,8 +78,6 @@ export default class MainPage extends BasePage {
         scheduleWeek
       })
       console.log(this.state.banner)
-    }).fail(() => {
-      alert(1111)
     })
   }
 
@@ -244,7 +247,7 @@ export default class MainPage extends BasePage {
             height: Dimensions.getHeight(86),
             marginRight: 12
           }}
-          onPress={() => this.toNextPage('SchedulePage',{id})}
+          onPress={() => this.toNextPage('SchedulePage', { id })}
           key={index}
           activeOpacity={1}
         >

+ 6 - 4
pages/services/library.js

@@ -1,12 +1,14 @@
 import APIConfig from './api.js';
 import efunRequest from '../utils/efunRequest'
+import request from '../utils/request'
 
 export default class LibraryUrl {
     
-    static getIndex(ageGroup) {
-        return efunRequest.getHttpRequest().url(APIConfig.getLibraryUrl(`/category`)).params({
-            ageGroup
-        }).get();
+    static  getIndex(ageGroup) {
+        // return efunRequest.getHttpRequest().url(APIConfig.getLibraryUrl(`/category`)).params({
+        //     ageGroup
+        // }).get();
+        return  request(APIConfig.getLibraryUrl(`/category?ageGroup=${ageGroup}`))
     }
     
 }

+ 6 - 0
pages/utils/efunRequest.js

@@ -12,6 +12,10 @@ class efunRequest {
         this._onSuccess = null;
         this._onFailed = null;
         this._deserialize = null;
+        // 异步获取的
+        this.uid = storage.load({
+            key: 'uid'
+        })
     }
 
     request(method) {
@@ -30,6 +34,8 @@ class efunRequest {
         this.xmlHTTPRequest = new XMLHttpRequest();
         this.xmlHTTPRequest.open(method, this._url + '?' + paramStr(), true);
         this.xmlHTTPRequest.setRequestHeader('Content-Type', 'application/' + (method == 'POST' || method == 'PUT' ? 'x-www-form-urlencoded' : 'text'));
+        this.xmlHTTPRequest.setRequestHeader('uid', this.uid ? this.uid : '');
+
 
         for (let key in this._header) {
             this.xmlHTTPRequest.setRequestHeader(key, this._header[key]);

+ 74 - 0
pages/utils/request.js

@@ -0,0 +1,74 @@
+/**
+ * 检查HTTP请求状态
+ */
+function checkStatus(response) {
+    if (response.status >= 200 && response.status < 300) {
+        return response;
+    }
+    const error = new Error(response.statusText);
+    error.response = response;
+    throw error;
+}
+
+/**
+ * 将Response内容转为JSON格式
+ */
+function parseJSON(response) {
+    return response.json();
+}
+
+/**
+ * 统一拦截接口返回数据的状态,提示错误消息
+ */
+function checkAPIDatas(data) {
+    console.log('data',data)
+    if (!data.success) {
+        const code = data;
+    }
+    return data
+}
+
+function checkAPIError(err) {
+    const code = err.response.code;
+    const status = err.response.status;
+    // const { url, type, oStatus, statusText } = err.response;
+    // Message.error(`地址:${url} 类型:${type} 状态:${oStatus} 信息:${statusText}`, 10);
+    return {
+        err
+    };
+
+}
+
+
+/**
+ * Requests a URL, returning a promise.
+ * @param  {string} url       The URL we want to request
+ * @param  {object} [options] The options we want to pass to "fetch"
+ * @return {object}           An object containing either "data" or "err"
+ */
+
+const request = async (url, options,callBack) => {
+    if (options) {
+        const method = options.method.toUpperCase();
+        if (method === 'POST' || method === 'PATCH' || method === 'DELETE' || method === 'PUT') {
+            options.headers = {
+                'Content-Type': 'application/json',
+                'token': await storage.load({
+                    key: 'token'
+                })
+            };
+        } else {
+            options.headers = {
+                'token': await storage.load({
+                    key: 'token'
+                })
+            };
+        }
+    }
+    return fetch(url, options)
+        .then(checkStatus)
+        .then(parseJSON)
+        .then(checkAPIDatas)
+        .catch(checkAPIError);
+}
+export default request