@fairys/taro-tools-react 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,18 @@
1
- import { proxy, useSnapshot } from "valtio";
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { proxy, ref as external_valtio_ref, useSnapshot } from "valtio";
2
3
  import { ProxyInstanceObjectBase } from "../utils/valtio/instance.js";
3
- import { useRef } from "react";
4
+ import { createContext, useContext, useEffect, useMemo, useRef } from "react";
4
5
  import utils_navigate from "../utils/navigate.js";
5
6
  import { globalDataInstance } from "./global.data.instance.js";
6
7
  import { globalSettingDataInstance } from "./global.setting.data.instance.js";
7
- class PageInfoDataInstance extends ProxyInstanceObjectBase {
8
+ import taro, { useDidShow } from "@tarojs/taro";
9
+ class page_info_data_instance_PageInfoDataInstance extends ProxyInstanceObjectBase {
10
+ notRefFields = [
11
+ 'loading'
12
+ ];
8
13
  defaultInital = {
9
14
  editType: 'add',
10
- editFormData: {},
15
+ editFormData: external_valtio_ref({}),
11
16
  isInfoSuccess: false,
12
17
  loading: {
13
18
  pageLoading: false
@@ -15,11 +20,15 @@ class PageInfoDataInstance extends ProxyInstanceObjectBase {
15
20
  };
16
21
  requestInfoConfig;
17
22
  requestSaveInfoConfig = {};
18
- constructor(options){
19
- super();
23
+ ctor(options) {
24
+ if (options?.isProxy) {
25
+ this.notRefFields = [
26
+ 'editFormData',
27
+ 'loading'
28
+ ];
29
+ this.store.editFormData = {};
30
+ }
20
31
  if (options?.initialValues) this.main_page_store(options.initialValues);
21
- if (options.requestInfoConfig) this.requestInfoConfig = options.requestInfoConfig || {};
22
- if (options.requestSaveInfoConfig) this.requestSaveInfoConfig = options.requestSaveInfoConfig || {};
23
32
  }
24
33
  store = proxy({
25
34
  ...this.defaultInital
@@ -42,15 +51,18 @@ class PageInfoDataInstance extends ProxyInstanceObjectBase {
42
51
  };
43
52
  main_getInfo = async ()=>{
44
53
  if (!this.requestInfoConfig?.getInfo) return void console.error("\u672A\u914D\u7F6E requestInfoConfig.getInfo \u8BF7\u6C42\u65B9\u6CD5");
54
+ taro.showLoading({
55
+ title: "\u52A0\u8F7D\u4E2D..."
56
+ });
45
57
  try {
46
58
  this.updatedLoading(true);
47
59
  let newParams = {};
48
- if (this.requestInfoConfig?.onBefore) newParams = await this.requestInfoConfig.onBefore(this.store);
49
- const result = await this.requestInfoConfig.getInfo?.(newParams);
60
+ if (this.requestInfoConfig?.onBefore) newParams = await this.requestInfoConfig.onBefore(this.store, this);
61
+ const result = await this.requestInfoConfig.getInfo?.(newParams, this);
50
62
  this.updatedLoading(false);
51
63
  if (result && result.code === globalSettingDataInstance.store.requestSuccessCode) {
52
64
  let saveData = {};
53
- saveData = this.requestInfoConfig?.onAfter ? this.requestInfoConfig.onAfter(result) : {
65
+ saveData = this.requestInfoConfig?.onAfter ? this.requestInfoConfig.onAfter(result, this) : {
54
66
  editFormData: {
55
67
  ...result?.data
56
68
  }
@@ -59,24 +71,33 @@ class PageInfoDataInstance extends ProxyInstanceObjectBase {
59
71
  ...saveData,
60
72
  isInfoSuccess: true
61
73
  });
62
- } else if (this.requestInfoConfig?.onError) this.requestInfoConfig.onError(result);
74
+ } else if (this.requestInfoConfig?.onError) this.requestInfoConfig.onError(result, this);
63
75
  } catch (error) {
64
76
  console.log(error);
65
77
  this.updatedLoading(false);
66
78
  }
79
+ taro.hideLoading();
67
80
  };
68
81
  main_saveInfo = async ()=>{
82
+ if (this.requestSaveInfoConfig?.onSaveInfo) return void console.error("\u672A\u914D\u7F6E requestSaveInfoConfig.onSaveInfo \u8BF7\u6C42\u65B9\u6CD5");
69
83
  try {
70
- if (this.requestSaveInfoConfig?.onSaveInfo) return void console.error("\u672A\u914D\u7F6E requestSaveInfoConfig.onSaveInfo \u8BF7\u6C42\u65B9\u6CD5");
71
84
  this.updatedLoading(true);
72
- const newParams = await this.requestSaveInfoConfig?.onSaveBefore?.(this.store) || this.store.editFormData || {};
73
- const result = await this.requestSaveInfoConfig.onSaveInfo?.(newParams);
85
+ taro.showLoading({
86
+ title: "\u4FDD\u5B58\u4E2D..."
87
+ });
88
+ const newParams = await this.requestSaveInfoConfig?.onSaveBefore?.(this.store, this) || this.store.editFormData || {};
89
+ const result = await this.requestSaveInfoConfig.onSaveInfo?.(newParams, this);
90
+ taro.hideLoading();
74
91
  this.updatedLoading(false);
75
92
  if (result && result.code === globalSettingDataInstance.store.requestSuccessCode) {
76
- if (this.requestSaveInfoConfig?.isShowSuccessMessage !== false) globalDataInstance.showMessage({
93
+ if (this.requestSaveInfoConfig?.isShowSuccessMessage === false) globalDataInstance.showMessage({
77
94
  content: result.message || "\u4FDD\u5B58\u6210\u529F"
78
95
  });
79
- if (this.requestSaveInfoConfig?.onSaveAfter) this.requestSaveInfoConfig.onSaveAfter(result);
96
+ else taro.showToast({
97
+ title: result.message || "\u4FDD\u5B58\u6210\u529F",
98
+ icon: 'none'
99
+ });
100
+ if (this.requestSaveInfoConfig?.onSaveAfter) this.requestSaveInfoConfig.onSaveAfter(result, this);
80
101
  const saveSuccessNavigate = this.requestSaveInfoConfig?.saveSuccessNavigate;
81
102
  if (saveSuccessNavigate) {
82
103
  if ('navigateBack' === saveSuccessNavigate) utils_navigate.navigateBack();
@@ -88,20 +109,58 @@ class PageInfoDataInstance extends ProxyInstanceObjectBase {
88
109
  url: saveSuccessNavigate
89
110
  });
90
111
  }
91
- } else if (this.requestSaveInfoConfig?.onSaveError) this.requestSaveInfoConfig.onSaveError(result);
112
+ } else if (this.requestSaveInfoConfig?.onSaveError) this.requestSaveInfoConfig.onSaveError(result, this);
92
113
  } catch (error) {
93
114
  console.log(error);
94
115
  this.updatedLoading(false);
95
116
  }
96
117
  };
97
118
  }
98
- const usePageInfoData = (options = {})=>{
99
- const pageDataInstance = useRef(new PageInfoDataInstance(options)).current;
100
- const store = useSnapshot(pageDataInstance.store);
119
+ const usePageInfoDataInstance = (instance)=>{
120
+ const ref = useRef();
121
+ if (!ref.current) if (instance) ref.current = instance;
122
+ else ref.current = new page_info_data_instance_PageInfoDataInstance();
123
+ return ref.current;
124
+ };
125
+ const PageInfoDataInstanceContext = /*#__PURE__*/ createContext(new page_info_data_instance_PageInfoDataInstance());
126
+ const usePageInfoDataInstanceContext = ()=>{
127
+ const PageInfoDataInstance = useContext(PageInfoDataInstanceContext);
128
+ return PageInfoDataInstance;
129
+ };
130
+ function PageInfoDataInstanceContextProvider(props) {
131
+ const { instance, children, initialValues, requestInfoConfig, requestSaveInfoConfig, isProxy, title, isMountRequestInfo, useHooks } = props;
132
+ const pageInfoInstance = usePageInfoDataInstance(instance);
133
+ pageInfoInstance.requestInfoConfig = requestInfoConfig;
134
+ pageInfoInstance.requestSaveInfoConfig = requestSaveInfoConfig;
135
+ useMemo(()=>pageInfoInstance.ctor({
136
+ initialValues,
137
+ isProxy
138
+ }), [
139
+ pageInfoInstance
140
+ ]);
141
+ useHooks?.(pageInfoInstance);
142
+ useDidShow(()=>{
143
+ if (title) taro.setNavigationBarTitle({
144
+ title
145
+ });
146
+ });
147
+ useEffect(()=>{
148
+ if (isMountRequestInfo) pageInfoInstance.main_getInfo();
149
+ }, []);
150
+ return /*#__PURE__*/ jsx(PageInfoDataInstanceContext.Provider, {
151
+ value: pageInfoInstance,
152
+ children: children
153
+ });
154
+ }
155
+ const usePageInfoDataInstanceState = ()=>{
156
+ const PageInfoDataInstance = usePageInfoDataInstanceContext();
157
+ const store = useSnapshot(PageInfoDataInstance.store, {
158
+ sync: true
159
+ });
101
160
  return [
102
161
  store,
103
- pageDataInstance,
162
+ PageInfoDataInstance,
104
163
  store.__defaultValue
105
164
  ];
106
165
  };
107
- export { PageInfoDataInstance, usePageInfoData };
166
+ export { page_info_data_instance_PageInfoDataInstance as PageInfoDataInstance, PageInfoDataInstanceContext, PageInfoDataInstanceContextProvider, usePageInfoDataInstance, usePageInfoDataInstanceContext, usePageInfoDataInstanceState };
@@ -2,6 +2,8 @@
2
2
  * 单个proxy对象数据基础实例封装
3
3
  */
4
4
  export declare class ProxyInstanceObjectBase<T extends Object = any> {
5
+ /**不使用ref存储的字段*/
6
+ notRefFields: string[];
5
7
  /**proxy 可状态更新字段 */
6
8
  store: T;
7
9
  /**初始化存储值*/
@@ -1,6 +1,7 @@
1
1
  import { proxy, ref } from "valtio";
2
2
  import react from "react";
3
3
  class ProxyInstanceObjectBase {
4
+ notRefFields = [];
4
5
  store = proxy({});
5
6
  _ctor = (inital, fields)=>{
6
7
  this._setValues(inital || {}, fields);
@@ -11,6 +12,7 @@ class ProxyInstanceObjectBase {
11
12
  Object.keys(values).forEach((key)=>{
12
13
  const value = values[key];
13
14
  if (Array.isArray(fields) && fields.includes(key)) this.store[key] = values[key];
15
+ else if (Array.isArray(this.notRefFields) && this.notRefFields.includes(key)) this.store[key] = value;
14
16
  else if (react.isValidElement(value) || 'function' == typeof value) this.store[key] = ref(values[key]);
15
17
  else if ('object' == typeof value && null !== value) this.store[key] = ref(values[key]);
16
18
  else this.store[key] = values[key];
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "author": "SunLxy <1011771396@qq.com>",
4
4
  "description": "框架组件库",
5
5
  "homepage": "https://github.com/autumn-fairy-tales/fairys-taro-react",
6
- "version": "0.0.7",
6
+ "version": "0.0.9",
7
7
  "main": "lib/index.js",
8
8
  "types": "esm/index.d.ts",
9
9
  "module": "esm/index.js",
@@ -0,0 +1,477 @@
1
+ import { proxy, ref, useSnapshot } from 'valtio';
2
+ import { ProxyInstanceObjectBase } from 'utils/valtio/instance';
3
+ import { createContext, useContext, useMemo, useRef } from 'react';
4
+ import { globalSettingDataInstance } from './global.setting.data.instance';
5
+ import Taro, { useDidShow } from '@tarojs/taro';
6
+
7
+ export interface PageDataInstanceState extends Object {
8
+ /**loading存储*/
9
+ loading?: Record<string, boolean>;
10
+ /**当前页*/
11
+ page?: number;
12
+ /**分页数*/
13
+ pageSize?: number;
14
+ /**默认分页数*/
15
+ defaultPageSize?: number;
16
+ /**总数*/
17
+ total?: number;
18
+ /**是否最后一页*/
19
+ hasLastPage?: boolean;
20
+ /**查询条件*/
21
+ search?: Object;
22
+ /**表格数据*/
23
+ dataList?: any[];
24
+ /**选择行数据*/
25
+ selectedRows?: any[];
26
+ selectedRowKeys?: any[];
27
+ /**一下是tab多页签使用*/
28
+ tabKey?: string;
29
+ /**tab多页签配置*/
30
+ tabItems?: {
31
+ /**tab页签key*/
32
+ key: string;
33
+ /**tab页签显示名称*/
34
+ label: string;
35
+ /**tab页签接口*/
36
+ api?: (
37
+ payload: any,
38
+ tabKey: string,
39
+ instance: PageDataInstance,
40
+ ) => Promise<{ code?: number; data?: any; message?: string }>;
41
+ /**tab页签默认查询参数*/
42
+ query?: Record<string, any>;
43
+ [s: string]: any;
44
+ }[];
45
+ /**是否是tab多页签*/
46
+ isTabs?: boolean;
47
+ /**是否展开查询条件*/
48
+ expandSearch?: boolean;
49
+ /**数据默认值不使用*/
50
+ __defaultValue?: string;
51
+ [s: string]: any;
52
+ }
53
+
54
+ export class PageDataInstance<
55
+ T extends PageDataInstanceState = PageDataInstanceState,
56
+ > extends ProxyInstanceObjectBase<T> {
57
+ /**不使用ref存储的字段*/
58
+ notRefFields: string[] = ['search', 'loading'];
59
+ // ======================================挂载方法或参数======================================
60
+ /**请求之前处理参数*/
61
+ onBefore?: (payload: any, store: T, instance: PageDataInstance<T>) => Partial<T>;
62
+ /**请求接口*/
63
+ getList?: (payload: any, instance: PageDataInstance<T>) => Promise<{ code?: number; data?: any; message?: string }>;
64
+ /**请求之后处理返回值进行存储*/
65
+ onAfter?: (data: Record<string, any>, instance: PageDataInstance<T>) => Partial<T>;
66
+ /** code!==1 时 触发*/
67
+ onError?: (data: Record<string, any>, instance: PageDataInstance<T>) => void;
68
+ /**重置获取值的方法*/
69
+ getResetValues?: (instance: PageDataInstance<T>) => Record<string, any>;
70
+ /**默认查询参数*/
71
+ defaultQuery?: Record<string, any> = {};
72
+ /**那些字段取值对象 code值*/
73
+ codeFields?: string[] = [];
74
+ /**那些字段取值对象的 value 值 */
75
+ valueFields?: string[] = [];
76
+ // ======================================挂载方法或参数======================================
77
+ /**是否滚动加载分页*/
78
+ is_scroll_page = true;
79
+ /**默认值*/
80
+ defaultInital = {
81
+ /**当前页*/
82
+ page: 1,
83
+ /**分页数*/
84
+ pageSize: 10,
85
+ /**总数*/
86
+ total: 0,
87
+ /**查询条件*/
88
+ search: {},
89
+ /**表格数据*/
90
+ dataList: ref([]),
91
+ /**选择行数据*/
92
+ selectedRows: ref([]),
93
+ selectedRowKeys: ref([]),
94
+ /**加载状态*/
95
+ loading: { pageLoading: false },
96
+ /**是否最后一页*/
97
+ hasLastPage: false,
98
+ } as unknown as T;
99
+ store = proxy<T>({ ...this.defaultInital } as T);
100
+
101
+ ctor = (options?: PageDataOptions<T>) => {
102
+ if (options?.initialValues) {
103
+ this.main_page_store(options.initialValues);
104
+ }
105
+ if (options.defaultPageSize) {
106
+ this.store.defaultPageSize = options.defaultPageSize;
107
+ }
108
+ if (options?.is_scroll_page !== undefined) {
109
+ this.is_scroll_page = options?.is_scroll_page;
110
+ }
111
+ if (options?.defaultTabKey) {
112
+ this.store.tabKey = options.defaultTabKey;
113
+ }
114
+ if (options?.tabItems) {
115
+ this.store.tabItems = ref(options.tabItems);
116
+ this.store.isTabs = Array.isArray(options.tabItems) && options.tabItems.length > 0;
117
+ }
118
+ };
119
+ /**初始化状态值*/
120
+ main_page_store = (initalValues: Partial<T> = {}, file?: string[]) => {
121
+ const newStore = { ...this.defaultInital, ...initalValues } as unknown as T;
122
+ return this._ctor(newStore, [...(file || []), 'loading']);
123
+ };
124
+ /**格式化请求参数*/
125
+ formateParams = (params: Record<string, any>) => {
126
+ const _query = {};
127
+ const keys = Object.keys(params);
128
+ for (let index = 0; index < keys.length; index++) {
129
+ const key = keys[index];
130
+ if ((this.valueFields || []).includes(key)) {
131
+ _query[key] = params[key]?.value;
132
+ } else if ((this.codeFields || []).includes(key)) {
133
+ _query[key] = params[key]?.code;
134
+ } else {
135
+ _query[key] = params[key];
136
+ }
137
+ }
138
+ return { ..._query };
139
+ };
140
+ /**更新查询条件*/
141
+ updatedSearch = (value: Record<string, any> = {}) => {
142
+ const keys = Object.keys(value);
143
+ if (!this.store.search) {
144
+ this.store.search = {};
145
+ }
146
+ for (let index = 0; index < keys.length; index++) {
147
+ const key = keys[index];
148
+ this.store.search[key] = value[key];
149
+ }
150
+ };
151
+
152
+ /**更新页面级的 pageLoading */
153
+ updatedPageLoading = (loading: boolean = true) => {
154
+ if (typeof this.store?.loading === 'object') {
155
+ this.store.loading.pageLoading = loading;
156
+ } else {
157
+ this.store.loading = { pageLoading: loading };
158
+ }
159
+ };
160
+ /**更新页面级的 loadMore */
161
+ updatedLoading = (value: Record<string, boolean>) => {
162
+ if (typeof this.store?.loading === 'object') {
163
+ this.store.loading = { ...this.store.loading, ...value };
164
+ } else {
165
+ this.store.loading = { ...value };
166
+ }
167
+ };
168
+ /**内置——查询列表*/
169
+ main_getList = async () => {
170
+ let pageField = 'page';
171
+ let pageSizeField = 'pageSize';
172
+ let dataListField = 'dataList';
173
+ let totalField = 'total';
174
+ let selectedRowsField = 'selectedRows';
175
+ let selectedRowKeysField = 'selectedRowKeys';
176
+ let _request: Function | undefined;
177
+ /**默认请求参数*/
178
+ let defaultQuery = {};
179
+ if (this.store.isTabs) {
180
+ const tabKey = this.store.tabKey;
181
+ const findTab = this.store.tabItems?.find((item) => item.key === tabKey);
182
+ if (findTab?.api) {
183
+ _request = findTab.api;
184
+ }
185
+ defaultQuery = findTab?.query || {};
186
+ pageField = `${tabKey}Page`;
187
+ pageSizeField = `${tabKey}PageSize`;
188
+ dataListField = `${tabKey}DataList`;
189
+ totalField = `${tabKey}Total`;
190
+ selectedRowsField = `${tabKey}SelectedRows`;
191
+ selectedRowKeysField = `${tabKey}SelectedRowKeys`;
192
+ } else {
193
+ _request = this.getList;
194
+ }
195
+ if (!_request) {
196
+ console.error('未配置 getList 请求方法,请检查是否配置了 getList 方法');
197
+ return;
198
+ }
199
+ Taro.showLoading({
200
+ title: '加载中...',
201
+ });
202
+ try {
203
+ this.updatedPageLoading(true);
204
+ const payload = {
205
+ ...this.defaultQuery,
206
+ ...defaultQuery,
207
+ ...this.store.search,
208
+ page: this.store[pageField] || 1,
209
+ pageSize: this.store[pageSizeField] || this.store.defaultPageSize || 20,
210
+ };
211
+ let newParams = this.formateParams({ ...payload }) as any;
212
+ if (this.onBefore) {
213
+ newParams = this.onBefore(payload, this.store, this);
214
+ }
215
+ const result = await this.getList?.(newParams, this);
216
+ this.updatedPageLoading(false);
217
+ this.store.loading.loadMore = false;
218
+ if (result && result.code === globalSettingDataInstance.store.requestSuccessCode) {
219
+ let saveData = {};
220
+ if (this.onAfter) {
221
+ saveData = this.onAfter(result, this);
222
+ } else {
223
+ const dataList = result?.data?.list || result?.data?.rows || result?.data?.records || [];
224
+ /**如果是第一页则直接返回数据,否则进行拼接数据*/
225
+ let newDataList = [];
226
+ if (this.store[pageField] === 1) {
227
+ newDataList = dataList;
228
+ } else if (this.is_scroll_page) {
229
+ newDataList = [...(this.store[dataListField] || []), ...dataList];
230
+ }
231
+ saveData = {
232
+ [dataListField]: newDataList,
233
+ [totalField]: result?.data?.total || 0,
234
+ };
235
+ // 第一页清理
236
+ if (this.store[pageField] === 1) {
237
+ saveData[selectedRowsField] = ref([]);
238
+ saveData[selectedRowKeysField] = ref([]);
239
+ }
240
+ }
241
+ if (saveData) this._setValues(saveData);
242
+ } else if (this.onError) {
243
+ this.onError(result, this);
244
+ }
245
+ } catch (error) {
246
+ console.log(error);
247
+ this.store.loading.loadMore = false;
248
+ this.updatedPageLoading(false);
249
+ }
250
+ Taro.hideLoading();
251
+ };
252
+ /**内置——翻页*/
253
+ main_onPageChange = (page: number) => {
254
+ if (this.store.isTabs) {
255
+ const tabKey = this.store.tabKey;
256
+ this._setValues({
257
+ [`${tabKey}Page`]: 1,
258
+ });
259
+ } else {
260
+ this._setValues({ page });
261
+ }
262
+ this.main_getList();
263
+ };
264
+ /**内置——翻页切换*/
265
+ main_onShowSizeChange = (_: number, pageSize: number) => {
266
+ if (this.store.isTabs) {
267
+ const tabKey = this.store.tabKey;
268
+ this._setValues({
269
+ [`${tabKey}Page`]: 1,
270
+ [`${tabKey}PageSize`]: pageSize,
271
+ });
272
+ } else {
273
+ this._setValues({ page: 1, pageSize });
274
+ }
275
+ this.main_getList();
276
+ };
277
+ /**弹框内字段重置,如果没有获取字段值的方法,则直接清理所有字段值*/
278
+ main_onReset = () => {
279
+ if (this.getResetValues) {
280
+ const values = this.getResetValues(this);
281
+ if (values) {
282
+ this.updatedSearch({ ...values });
283
+ }
284
+ } else {
285
+ // 清理所有字段值
286
+ const keys = Object.keys(this.store.search || {});
287
+ for (let index = 0; index < keys.length; index++) {
288
+ const key = keys[index];
289
+ this.store.search[key] = undefined;
290
+ }
291
+ }
292
+ };
293
+ /**内置——查询方法*/
294
+ main_onSearch = () => {
295
+ this.main_onPageChange(1);
296
+ /**点击查询的时候关闭弹框*/
297
+ this.store.expandSearch = false;
298
+ };
299
+ /**加载更多*/
300
+ main_onLoadMore = () => {
301
+ if (this.store.loading?.pageLoading) {
302
+ // 加载中,不进行请求
303
+ return;
304
+ }
305
+ const isTabs = this.store.isTabs;
306
+ if (isTabs) {
307
+ const tabKey = this.store.tabKey;
308
+ const total = this.store[`${tabKey}Total`] || 0;
309
+ const page = this.store[`${tabKey}Page`] || 1;
310
+ const pageSize = this.store[`${tabKey}PageSize`] || this.store.defaultPageSize || 20;
311
+ const count = Math.ceil(total / pageSize);
312
+ let hasLastPage = false;
313
+ if (page >= count && total) {
314
+ // 已经最后一页数据了
315
+ hasLastPage = true;
316
+ this._setValues({ [`${tabKey}HasLastPage`]: hasLastPage });
317
+ return;
318
+ }
319
+ const nextPage = page + 1;
320
+ if (nextPage >= count && total) {
321
+ // 当前是最后一页数据
322
+ hasLastPage = true;
323
+ }
324
+ this.updatedLoading({ [`${tabKey}LoadMore`]: true });
325
+ // 判断是否最后一页数据
326
+ this._setValues({
327
+ [`${tabKey}Page`]: nextPage,
328
+ [`${tabKey}HasLastPage`]: hasLastPage,
329
+ });
330
+ this.main_getList();
331
+ return;
332
+ }
333
+ const total = this.store.total || 0;
334
+ const page = this.store.page || 1;
335
+ const pageSize = this.store.pageSize || this.store.defaultPageSize || 20;
336
+ const count = Math.ceil(total / pageSize);
337
+ let hasLastPage = false;
338
+ if (page >= count && total) {
339
+ // 已经最后一页数据了
340
+ hasLastPage = true;
341
+ this._setValues({ hasLastPage });
342
+ return;
343
+ }
344
+ const nextPage = page + 1;
345
+ if (nextPage >= count && total) {
346
+ // 当前是最后一页数据
347
+ hasLastPage = true;
348
+ }
349
+ this.store.loading.loadMore = true;
350
+ // 判断是否最后一页数据
351
+ this._setValues({ page: nextPage, hasLastPage });
352
+ this.main_getList();
353
+ };
354
+ }
355
+
356
+ export interface PageDataOptions<T extends PageDataInstanceState = PageDataInstanceState> {
357
+ /**初始值*/
358
+ initialValues?: Partial<T>;
359
+ /**是否滚动加载更多*/
360
+ is_scroll_page?: boolean;
361
+ /**默认tab key*/
362
+ defaultTabKey?: string;
363
+ /**tab多页签配置*/
364
+ tabItems?: PageDataInstanceState['tabItems'];
365
+ /**默认分页数*/
366
+ defaultPageSize?: number;
367
+ }
368
+
369
+ /**初始化实例*/
370
+ export function usePageDataInstance<T extends PageDataInstanceState = PageDataInstanceState>(
371
+ instance?: PageDataInstance<T>,
372
+ ) {
373
+ const ref = useRef<PageDataInstance<T>>();
374
+ if (!ref.current) {
375
+ ref.current = instance || new PageDataInstance<T>();
376
+ }
377
+ return ref.current;
378
+ }
379
+
380
+ /**页面级数据状态管理上下文*/
381
+ export const PageDataInstanceContext = createContext<PageDataInstance>(new PageDataInstance());
382
+
383
+ /**获取上下文实例*/
384
+ export const usePageDataInstanceContext = <T extends PageDataInstanceState = PageDataInstanceState>() => {
385
+ const PageDataInstance = useContext(PageDataInstanceContext) as PageDataInstance<T>;
386
+ return PageDataInstance;
387
+ };
388
+
389
+ export interface PageDataInstanceContextProviderProps<T extends PageDataInstanceState = PageDataInstanceState>
390
+ extends PageDataOptions<T> {
391
+ instance?: PageDataInstance<T>;
392
+ children: React.ReactNode;
393
+ /**请求之前处理参数*/
394
+ onBefore?: PageDataInstance<T>['onBefore'];
395
+ /**请求接口*/
396
+ getList?: PageDataInstance<T>['getList'];
397
+ /**请求之后处理返回值进行存储*/
398
+ onAfter?: PageDataInstance<T>['onAfter'];
399
+ /** code!== 200 时 触发*/
400
+ onError?: PageDataInstance<T>['onError'];
401
+ /**获取弹框内重置参数*/
402
+ getResetValues?: PageDataInstance<T>['getResetValues'];
403
+ /**默认查询参数*/
404
+ defaultQuery?: PageDataInstance<T>['defaultQuery'];
405
+ /**那些字段取值对象 code值*/
406
+ codeFields?: PageDataInstance<T>['codeFields'];
407
+ /**那些字段取值对象的 value 值 */
408
+ valueFields?: PageDataInstance<T>['valueFields'];
409
+ /**是否是第一次加载*/
410
+ isMountLoad?: boolean;
411
+ /**页面标题*/
412
+ title?: string;
413
+ }
414
+
415
+ /**页面级数据状态管理上下文提供者*/
416
+ export function PageDataInstanceContextProvider<T extends PageDataInstanceState = PageDataInstanceState>(
417
+ props: PageDataInstanceContextProviderProps<T>,
418
+ ) {
419
+ const {
420
+ instance,
421
+ children,
422
+ initialValues,
423
+ is_scroll_page,
424
+ defaultTabKey,
425
+ tabItems,
426
+ defaultPageSize,
427
+ onBefore,
428
+ getList,
429
+ onAfter,
430
+ onError,
431
+ getResetValues,
432
+ defaultQuery,
433
+ codeFields,
434
+ valueFields,
435
+ isMountLoad,
436
+ title,
437
+ } = props;
438
+ const pageInstance = usePageDataInstance(instance);
439
+
440
+ instance.onBefore = onBefore;
441
+ instance.getList = getList;
442
+ instance.onAfter = onAfter;
443
+ instance.onError = onError;
444
+ instance.getResetValues = getResetValues;
445
+ instance.codeFields = codeFields;
446
+ instance.valueFields = valueFields;
447
+ instance.defaultQuery = defaultQuery;
448
+
449
+ useMemo(
450
+ () => pageInstance.ctor({ initialValues, is_scroll_page, defaultTabKey, tabItems, defaultPageSize }),
451
+ [pageInstance],
452
+ );
453
+
454
+ useMemo(() => {
455
+ if (isMountLoad) {
456
+ pageInstance.main_onSearch();
457
+ }
458
+ }, []);
459
+
460
+ useDidShow(() => {
461
+ if (title) {
462
+ // 列表查询才调用
463
+ Taro.setNavigationBarTitle({ title });
464
+ }
465
+ });
466
+
467
+ return <PageDataInstanceContext.Provider value={pageInstance}>{children}</PageDataInstanceContext.Provider>;
468
+ }
469
+
470
+ /**
471
+ * 页面级数据状态管理
472
+ */
473
+ export const usePageDataInstanceState = <T extends PageDataInstanceState = PageDataInstanceState>() => {
474
+ const PageMainDataInstance = usePageDataInstanceContext<T>();
475
+ const store = useSnapshot(PageMainDataInstance.store, { sync: true }) as T;
476
+ return [store, PageMainDataInstance, store.__defaultValue] as [T, PageDataInstance<T>, string | undefined];
477
+ };