张延森 4 лет назад
Родитель
Сommit
25b2237a55
7 измененных файлов: 189 добавлений и 17 удалений
  1. 1
    1
      project.config.json
  2. 23
    8
      src/app.js
  3. 1
    2
      src/layouts/index.jsx
  4. 3
    1
      src/store/models/index.js
  5. 25
    0
      src/store/models/useSystem.js
  6. 16
    5
      src/store/models/useUser.js
  7. 120
    0
      src/utils/request.js

+ 1
- 1
project.config.json Просмотреть файл

@@ -2,7 +2,7 @@
2 2
 	"miniprogramRoot": "dist/",
3 3
 	"projectname": "miniapp",
4 4
 	"description": "",
5
-	"appid": "wx1d9348230d6a0da6",
5
+	"appid": "wxe44244d1a5ea3364",
6 6
 	"setting": {
7 7
 		"urlCheck": true,
8 8
 		"es6": false,

+ 23
- 8
src/app.js Просмотреть файл

@@ -1,19 +1,34 @@
1 1
 import React, { Component } from 'react'
2
-import { StoreRoot } from './store'
2
+import Taro from '@tarojs/taro'
3
+import { StoreRoot, store } from './store'
3 4
 import './app.less'
4 5
 
5 6
 class App extends Component {
6 7
 
7
-  onLaunch () {
8
-    // let Params = {}
9
-    // if (wx.getStorageSync('openid')) {
10
-    //   Params.token = wx.getStorageSync('openid')
11
-    // }
12
-    wx.setBackgroundFetchToken({ token: 'firstxsxs21515151551515' })
8
+  onLaunch (options) {
9
+    // 此处获取不到 state, 因为 app 不会刷新
10
+    const { setUser } = store.getModel('user').getState()
11
+    const { setSysInfo } = store.getModel('sys').getState()
12
+
13
+    // 预拉取数据
13 14
     wx.getBackgroundFetchData({
14 15
       fetchType: 'pre',
15 16
       success (res) {
16
-        console.log(res)
17
+        if (res.errMsg === 'getBackgroundFetchData:ok') {
18
+          const data = JSON.parse(res.fetchedData)
19
+          if (data.code === 1000) {
20
+            setSysInfo(data.data)
21
+          }
22
+        }
23
+      }
24
+    })
25
+
26
+    // 登录
27
+    Taro.login({
28
+      success: res => {
29
+        if (res.errMsg === 'login:ok') {
30
+          // res.code
31
+        }
17 32
       }
18 33
     })
19 34
   }

+ 1
- 2
src/layouts/index.jsx Просмотреть файл

@@ -5,8 +5,7 @@ import Spin from '@/components/Spin'
5 5
 export default function(props) {
6 6
   const { user } = useModel('user')
7 7
 
8
-  // const loading = !user || !user.personId
9
-  const loading = false
8
+  const loading = !user || !user.personId
10 9
 
11 10
   return (
12 11
     <Spin loading={loading}>{ props.children }</Spin>

+ 3
- 1
src/store/models/index.js Просмотреть файл

@@ -1,7 +1,9 @@
1
+import useSystem from './useSystem'
1 2
 import useUser from './useUser'
2 3
 
3 4
 const models = {
4
-  'user': useUser
5
+  'sys': useSystem,
6
+  'user': useUser,
5 7
 }
6 8
 
7 9
 export default models

+ 25
- 0
src/store/models/useSystem.js Просмотреть файл

@@ -0,0 +1,25 @@
1
+import React, { useEffect, useState } from 'react'
2
+import Taro from '@tarojs/taro'
3
+
4
+export default function useBar() {
5
+  const [sysInfo, setSysInfo] = useState()
6
+
7
+  // const updateSysInfo = data => {
8
+  //   // 固化到本地
9
+  //   Taro.setStorage({ key: 'sys', data })
10
+  //   setSysInfo(data)
11
+  // }
12
+
13
+  // useEffect(() => {
14
+  //   // 如果本地存在, 则读取本地信息
15
+  //   const u = Taro.getStorageSync('sys')
16
+  //   if (u) {
17
+  //     setSysInfo(u)
18
+  //   }
19
+  // }, [])
20
+
21
+  return {
22
+    sysInfo,
23
+    setSysInfo
24
+  }
25
+}

+ 16
- 5
src/store/models/useUser.js Просмотреть файл

@@ -1,14 +1,25 @@
1
-import React, { useState } from 'react'
1
+import React, { useEffect, useState } from 'react'
2
+import Taro from '@tarojs/taro'
2 3
 
3 4
 export default function useBar() {
4 5
   const [user, setUser] = useState({})
5 6
 
6
-  const signIn = () => {
7
-    // xxx
8
-  }
7
+  // const updateUser = data => {
8
+  //   // 固化到本地
9
+  //   Taro.setStorage({ key: 'user', data })
10
+  //   setUser(data)
11
+  // }
12
+
13
+  // useEffect(() => {
14
+  //   // 如果本地存在, 则读取本地信息
15
+  //   const u = Taro.getStorageSync('user')
16
+  //   if (u) {
17
+  //     setUser(u)
18
+  //   }
19
+  // }, [])
9 20
 
10 21
   return {
11 22
     user,
12
-    signIn
23
+    setUser
13 24
   }
14 25
 }

+ 120
- 0
src/utils/request.js Просмотреть файл

@@ -0,0 +1,120 @@
1
+import Taro from '@tarojs/taro'
2
+
3
+const accountInfo = Taro.getAccountInfoSync()
4
+const appId = accountInfo.miniProgram.appId
5
+
6
+const query2String = query => {
7
+  return Object.entries(query || {}).map(pair => `${encodeURIComponent(pair[0])}=${encodeURIComponent(pair[1])}`).join('&')
8
+}
9
+
10
+const request = options => {
11
+  const { url, params, header, ...leftOpts } = options || {}
12
+
13
+  let realURL = url
14
+  if (!params) {
15
+    realURL += `?${query2String(params)}`
16
+  }
17
+
18
+  const token = Taro.getStorageSync('token')
19
+  const authHeader = token ? { authorization: `Bearer token` } : {}
20
+  const appHeader = { appId, 'x-action': 'miniapp' }
21
+
22
+  const config = {
23
+    url: realURL,
24
+    header: {
25
+      ...(header || {}),
26
+      ...authHeader,
27
+      ...appHeader,
28
+    },
29
+    ...leftOpts,
30
+  }
31
+
32
+  return new Promise((resolve, reject) => {
33
+    Taro.request({
34
+      ...config,
35
+      success: res => {
36
+        if (res.statusCode >= 300) {
37
+          const errMsg = `网络错误: ${res.statusCode}`
38
+          Taro.showToast({
39
+            title: errMsg,
40
+            icon: 'none',
41
+            duration: 3000
42
+          })
43
+          return
44
+        }
45
+
46
+        const { data, code, message } = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
47
+        if (code === 1000) {
48
+          resolve(data)
49
+        } else {
50
+          reject(message)
51
+        }
52
+      },
53
+      fail: err => {
54
+        console.error(err)
55
+
56
+        const message = err.errMsg || err.message || ''
57
+        const errMsg = message.indexOf('java') > -1 ? '服务内部错误' : `网络错误: ${message}`
58
+
59
+        Taro.showToast({
60
+          title: errMsg,
61
+          icon: 'none',
62
+          duration: 3000
63
+        })
64
+
65
+        // reject(err)
66
+      }
67
+    })
68
+  })
69
+}
70
+
71
+// request 不带 loading, 也不带错误处理
72
+export default request
73
+
74
+// 比 request 增加了 loading 以及 错误提示
75
+export function request2(options) {
76
+  const { showOk, okMessage, showLoading, ...config } = options || {}
77
+
78
+  // 默认自带 loading
79
+  if (showLoading !== false) {
80
+    Taro.showLoading({ title: '请求中' })
81
+  }
82
+
83
+  return new Promise((resolve, reject) => {
84
+    request(config).then(res => {
85
+      if (showLoading !== false) {
86
+        Taro.hideLoading()
87
+      }
88
+
89
+      if (showOk) {
90
+        const t = setTimeout(() => {
91
+          Taro.showToast({
92
+            title: okMessage || '操作成功',
93
+            icon: 'success',
94
+            duration: 2000
95
+          })
96
+
97
+          clearTimeout(t)
98
+        })
99
+      } else {
100
+        resolve(res)
101
+      }
102
+    }).catch(err => {
103
+      if (showLoading !== false) {
104
+        Taro.hideLoading()
105
+      }
106
+
107
+      const t = setTimeout(() => {
108
+        Taro.showToast({
109
+          title: err,
110
+          icon: 'none',
111
+          duration: 3000
112
+        })
113
+
114
+        clearTimeout(t)
115
+      })
116
+
117
+      reject(err)
118
+    })
119
+  })
120
+}