import BSL from 'bsl-core/typings'; import C from 'bsl-mp/app/Component'; import { clearTimeout, ListenerCallback, setTimeout } from 'bsl-mp/app/Scheduler'; import mpuseRequest, { Cancel, clearCache } from 'bsl-mp/app/useRequest'; import * as Export from './export'; const computedBehavior = require('miniprogram-computed').behavior; const state = { /** 请求状态 */ state: 'undefined' as BSL.RequestState, /** 用于触发重新请求 */ retryId: 0, /** 引用requestTask,用于取消请求 */ _cancelRef: { current: null } as Cancel, /** 用于比较新的props和旧的props */ _prevProps: { api: '', refreshId: 0, retryId: 0, disabled: false, cache: '', data: '' }, /** 是否已触发ready生命周期 */ _isReady: false, /** 定时器 */ _timer: null as ListenerCallback | null, _cacheKey: '' }; class Instance extends C { constructor() { super(state, { api: { type: String, value: '', }, header: { type: Object, value: undefined }, method: { type: String, value: 'get' }, /** 请求的参数 */ data: { type: Object, value: {} }, /** 用于重新发起请求 */ refreshId: { type: Number, value: 0, }, /** 是否缓存请求成功后的数据 * page: 页面级,request组件被卸载时清除 * app: 应用级,整个应用生命周期内存在 */ cache: { type: String, value: '' }, disabled: Boolean, useRetry: Boolean, transformResponse: { type: Function as any, value: null }, dataType: String, responseType: String, timeout: Number }); } public behaviors = [computedBehavior]; public options = { // 在组件定义时的选项中启用多slot支持 multipleSlots: true, // 指定所有 _ 开头的数据字段为纯数据字段 pureDataPattern: /^_/ }; public watch = { 'api, refreshId, retryId, disabled, cache, data'() { const self = this as any as Instance; const _prevProps = self.data._prevProps; if (self.data._isReady === false || self.properties.disabled) { return; } if ( _prevProps.api !== self.properties.api || _prevProps.refreshId !== self.properties.refreshId || _prevProps.cache !== self.properties.cache || _prevProps.data !== JSON.stringify(self.properties.data) || _prevProps.retryId !== self.data.retryId ) { self.effect(); self.setPrevProps(); } } } public created() { this.setPrevProps(); } public ready() { this.setData({ _isReady: true }); this.effect(); } public detached() { this.clearTimeout(); if (this.properties.cache === 'page' && this.data._cacheKey) { clearCache(this.data._cacheKey); } } /** 取消请求 */ public cancel() { if (this.data._cancelRef.current) { this.data._cancelRef.current.abort(); } } /** 在更新和初始化时触发 */ public effect() { const props = this.properties; if (props.disabled) { return; } // 在请求前取消上一个未完成的请求 this.cancel(); const timer = setTimeout(() => { if (this.data.state === 'undefined' || this.properties.refreshId !== props.refreshId) { this.setState('loading'); this.triggerEvent('loading', {}); } }, 300); const [request, cancel, keyRef] = mpuseRequest(); request(props).then((res) => { this.triggerEvent('finally', res); if (keyRef.current) { this.setData({ _cacheKey: keyRef.current }); } switch (res.code) { case 200: this.setState('complete'); this.triggerEvent('complete', res); break; case 401: this.setState('auth'); this.triggerEvent('notLogin', res); break; case 404: this.setState('empty'); this.triggerEvent('empty', res); break; default: // 500或其他码都视为fail状态 this.setState('fail'); this.triggerEvent('fail', res); break; } }).catch((err: { errMsg: string }) => { const message = err?.errMsg; if (message === 'request:fail abort') { return; } this.triggerEvent('finally', err); this.triggerEvent('catch', err); if (message?.includes('timeout of') && message?.includes('ms exceeded')) { this.setState('timeout'); this.triggerEvent('timeout', err); } else { this.setState('fail'); this.triggerEvent('fail', err); throw err; } }); this.groupSetData(() => { this.setPrevProps(); this.setData({ _cancelRef: cancel, _timer: timer }); }); } public setPrevProps() { this.setData({ _prevProps: { api: this.properties.api, refreshId: this.properties.refreshId, retryId: this.data.retryId, disabled: this.properties.disabled, cache: this.properties.cache, data: JSON.stringify(this.properties.data) } }); } public clearTimeout() { if (this.data._timer) { clearTimeout(this.data._timer); this.setData({ _timer: null }); } } /** 在请求完成之后设置请求状态 */ public setState(typeValue: BSL.RequestState) { this.groupSetData(() => { this.clearTimeout(); this.setData({ state: typeValue }); }); } /** 重新请求 */ public bindRetry() { const state = this.data.state; if ((state === 'fail' || state === 'timeout') && this.properties.useRetry) { this.setData({ state: 'undefined', retryId: this.data.retryId + 1 }); } } } Component(new Instance().init());