🌈 style(eslint): add eslint rules

This commit is contained in:
xuan
2022-11-26 14:35:05 +08:00
parent f3aa20f049
commit 99a920975f
245 changed files with 14909 additions and 14349 deletions
+46 -33
View File
@@ -1,5 +1,5 @@
import React, { useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import React, { useRef, useState } from 'react'
import { Command } from '@/common/bluetooth/command'
import { uint8ArrayToFloat32, uint8ArrayToHex, waitFor } from '@/common/bluetooth/utils'
@@ -33,13 +33,13 @@ interface stateStype {
/** 是否显示蓝牙调试信息 */
debug: any
//搜索到的设备
// 搜索到的设备
devices: any
//取色仪主动返回的数据
// 取色仪主动返回的数据
deviceLab: any
}
let stateObj: stateStype = {
const stateObj: stateStype = {
/** 事件监听器 */
listeners: new Set(),
/** 正在扫描设备 */
@@ -64,25 +64,26 @@ let stateObj: stateStype = {
/** 是否显示蓝牙调试信息 */
debug: true,
//搜索到的设备
// 搜索到的设备
devices: [],
//取色仪主动返回的数据
// 取色仪主动返回的数据
deviceLab: null,
}
export default (props) => {
let refStatus = useRef(stateObj)
let [state, setState] = useState(refStatus.current)
const refStatus = useRef(stateObj)
const [state, setState] = useState(refStatus.current)
const changeStatus = (obj: Object): void => {
refStatus.current = { ...refStatus.current, ...obj }
setState({ ...refStatus.current })
}
const init = async () => {
const init = async() => {
try {
await openAdapter()
} catch (e) {
}
catch (e) {
changeStatus({ available: false })
}
@@ -94,11 +95,12 @@ export default (props) => {
emit({ type: res.connected ? 'connected' : 'disconnect', detail: res })
})
Taro.onBLECharacteristicValueChange(({ value }) => notifySubscriber(value))
subscribe(async (ev) => {
subscribe(async(ev) => {
if (ev.type === 'stateUpdate') {
// 蓝牙状态发生的变化
changeStatus({ discovering: ev.detail.discovering, available: ev.detail.available })
} else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) {
}
else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) {
// 断开连接
changeStatus({
connected: null,
@@ -108,12 +110,14 @@ export default (props) => {
devices: [],
})
Taro.showToast({ icon: 'none', title: '蓝牙连接已断开' })
} else if (ev.type === 'connected' && refStatus.current.connecting) {
}
else if (ev.type === 'connected' && refStatus.current.connecting) {
// 连接成功
changeStatus({ connected: refStatus.current.connecting, connecting: null })
Taro.showToast({ title: '蓝牙已连接' })
} else if (ev.type === 'measure') {
//监听取色仪主动推送lab
}
else if (ev.type === 'measure') {
// 监听取色仪主动推送lab
await measureAndGetLab()
}
})
@@ -186,11 +190,11 @@ export default (props) => {
})
}
//获取搜索到的设备
// 获取搜索到的设备
const getDevices = (res) => {
res.devices.forEach((device) => {
// 排除掉已搜索到的设备和名称不合法的设备, 将新发现的设备添加到列表中
if (/^CM/.test(device.name) && !refStatus.current.devices.find((i) => i.deviceId === device.deviceId)) {
if (/^CM/.test(device.name) && !refStatus.current.devices.find(i => i.deviceId === device.deviceId)) {
changeStatus({ devices: [...refStatus.current.devices, device] })
}
})
@@ -200,7 +204,7 @@ export default (props) => {
* 连接设备
* @param {{ name: string, deviceId: string, RSSI: number }} device
*/
const connect = async (device) => {
const connect = async(device) => {
try {
changeStatus({ connecting: device })
console.log('connecting::', device)
@@ -208,7 +212,8 @@ export default (props) => {
await discoverService(device.deviceId)
await discoverCharacteristic(device.deviceId)
await notifyCharacteristicValueChange(device.deviceId)
} catch (e) {
}
catch (e) {
changeStatus({ connecting: null })
Taro.showToast({ icon: 'none', title: '蓝牙连接失败' })
throw e
@@ -216,8 +221,8 @@ export default (props) => {
}
/** 断开当前连接的设备 */
const disconnect = async () => {
if (!refStatus.current.connected && !refStatus.current.connecting) return
const disconnect = async() => {
if (!refStatus.current.connected && !refStatus.current.connecting) { return }
if (refStatus.current.connected) {
await closeConnection(refStatus.current.connected.deviceId)
resetCommand()
@@ -265,10 +270,11 @@ export default (props) => {
Taro.getBLEDeviceServices({
deviceId,
success: ({ services }) => {
const service = services.find((i) => refStatus.current.serviceRule.test(i.uuid))
const service = services.find(i => refStatus.current.serviceRule.test(i.uuid))
if (!service) {
reject(new Error('服务不可用'))
} else {
}
else {
changeStatus({ serviceId: service.uuid })
resolve(service)
}
@@ -285,10 +291,11 @@ export default (props) => {
deviceId,
serviceId: refStatus.current.serviceId,
success: ({ characteristics }) => {
const characteristic = characteristics.find((i) => refStatus.current.characteristicRule.test(i.uuid))
const characteristic = characteristics.find(i => refStatus.current.characteristicRule.test(i.uuid))
if (!characteristic) {
reject(new Error('特征不可用'))
} else {
}
else {
changeStatus({ characteristicId: characteristic.uuid })
resolve(characteristic)
}
@@ -325,14 +332,16 @@ export default (props) => {
if (refStatus.current.command.isComplete) {
if (refStatus.current.command.isValid && refStatus.current.responseResolve) {
refStatus.current.responseResolve(refStatus.current.command.response)
} else if (!refStatus.current.command.isValid) {
}
else if (!refStatus.current.command.isValid) {
refStatus.current.responseReject(new Error('无效数据'))
}
resetCommand()
}
} else {
}
else {
const uint8Array = new Uint8Array(buffer)
if (uint8Array[0] === 0xbb && uint8Array[1] === 1 && uint8Array[3] === 0) {
if (uint8Array[0] === 0xBB && uint8Array[1] === 1 && uint8Array[3] === 0) {
const ev = { type: 'measure', detail: { mode: uint8Array[2] } }
emit(ev)
}
@@ -345,10 +354,11 @@ export default (props) => {
* @returns {Promise<Uint8Array>}
*/
function exec(command) {
return new Promise(async (resolve, reject) => {
return new Promise(async(resolve, reject) => {
if (refStatus.current.command) {
reject(new Error('正在执行其他命令'))
} else {
}
else {
try {
refStatus.current.command = command
const data = command.data
@@ -359,7 +369,8 @@ export default (props) => {
if (command.responseSize <= 0) {
resolve(true)
resetCommand()
} else {
}
else {
refStatus.current.responseReject = reject
refStatus.current.responseResolve = resolve
refStatus.current.responseTimer = setTimeout(() => {
@@ -367,7 +378,8 @@ export default (props) => {
resetCommand()
}, command.timeout)
}
} catch (e) {
}
catch (e) {
reject(e)
}
}
@@ -471,7 +483,8 @@ export const useBluetoothTwo = () => {
const res = React.useContext<any>(Context)
if (res) {
return { ...res }
} else {
}
else {
return {}
}
}
+46 -33
View File
@@ -1,5 +1,5 @@
import React, { useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import React, { useRef, useState } from 'react'
import { Command } from '@/common/bluetooth/command'
import { uint8ArrayToFloat32, uint8ArrayToHex, waitFor } from '@/common/bluetooth/utils'
@@ -33,13 +33,13 @@ export interface BluetoothStateType {
/** 是否显示蓝牙调试信息 */
debug: any
//搜索到的设备
// 搜索到的设备
devices: any
//取色仪主动返回的数据
// 取色仪主动返回的数据
deviceLab: any
}
let stateObj: BluetoothStateType = {
const stateObj: BluetoothStateType = {
/** 事件监听器 */
listeners: new Set(),
/** 正在扫描设备 */
@@ -64,25 +64,26 @@ let stateObj: BluetoothStateType = {
/** 是否显示蓝牙调试信息 */
debug: true,
//搜索到的设备
// 搜索到的设备
devices: [],
//取色仪主动返回的数据
// 取色仪主动返回的数据
deviceLab: null,
}
export default (props) => {
let refStatus = useRef(stateObj)
let [state, setState] = useState(refStatus.current)
const refStatus = useRef(stateObj)
const [state, setState] = useState(refStatus.current)
const changeStatus = (obj: Object): void => {
refStatus.current = { ...refStatus.current, ...obj }
setState({ ...refStatus.current })
}
const init = async () => {
const init = async() => {
try {
await openAdapter()
} catch (e) {
}
catch (e) {
changeStatus({ available: false })
}
@@ -94,11 +95,12 @@ export default (props) => {
emit({ type: res.connected ? 'connected' : 'disconnect', detail: res })
})
Taro.onBLECharacteristicValueChange(({ value }) => notifySubscriber(value))
subscribe(async (ev) => {
subscribe(async(ev) => {
if (ev.type === 'stateUpdate') {
// 蓝牙状态发生的变化
changeStatus({ discovering: ev.detail.discovering, available: ev.detail.available })
} else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) {
}
else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) {
// 断开连接
changeStatus({
connected: null,
@@ -108,12 +110,14 @@ export default (props) => {
devices: [],
})
Taro.showToast({ icon: 'none', title: '蓝牙连接已断开' })
} else if (ev.type === 'connected' && refStatus.current.connecting) {
}
else if (ev.type === 'connected' && refStatus.current.connecting) {
// 连接成功
changeStatus({ connected: refStatus.current.connecting, connecting: null })
Taro.showToast({ title: '蓝牙已连接' })
} else if (ev.type === 'measure') {
//监听取色仪主动推送lab
}
else if (ev.type === 'measure') {
// 监听取色仪主动推送lab
await measureAndGetLab()
}
})
@@ -186,11 +190,11 @@ export default (props) => {
})
}
//获取搜索到的设备
// 获取搜索到的设备
const getDevices = (res) => {
res.devices.forEach((device) => {
// 排除掉已搜索到的设备和名称不合法的设备, 将新发现的设备添加到列表中
if (/^CM/.test(device.name) && !refStatus.current.devices.find((i) => i.deviceId === device.deviceId)) {
if (/^CM/.test(device.name) && !refStatus.current.devices.find(i => i.deviceId === device.deviceId)) {
changeStatus({ devices: [...refStatus.current.devices, device] })
}
})
@@ -200,7 +204,7 @@ export default (props) => {
* 连接设备
* @param {{ name: string, deviceId: string, RSSI: number }} device
*/
const connect = async (device) => {
const connect = async(device) => {
try {
changeStatus({ connecting: device })
console.log('connecting::', device)
@@ -208,7 +212,8 @@ export default (props) => {
await discoverService(device.deviceId)
await discoverCharacteristic(device.deviceId)
await notifyCharacteristicValueChange(device.deviceId)
} catch (e) {
}
catch (e) {
changeStatus({ connecting: null })
Taro.showToast({ icon: 'none', title: '蓝牙连接失败' })
throw e
@@ -216,8 +221,8 @@ export default (props) => {
}
/** 断开当前连接的设备 */
const disconnect = async () => {
if (!refStatus.current.connected && !refStatus.current.connecting) return
const disconnect = async() => {
if (!refStatus.current.connected && !refStatus.current.connecting) { return }
if (refStatus.current.connected) {
await closeConnection(refStatus.current.connected.deviceId)
resetCommand()
@@ -265,10 +270,11 @@ export default (props) => {
Taro.getBLEDeviceServices({
deviceId,
success: ({ services }) => {
const service = services.find((i) => refStatus.current.serviceRule.test(i.uuid))
const service = services.find(i => refStatus.current.serviceRule.test(i.uuid))
if (!service) {
reject(new Error('服务不可用'))
} else {
}
else {
changeStatus({ serviceId: service.uuid })
resolve(service)
}
@@ -285,10 +291,11 @@ export default (props) => {
deviceId,
serviceId: refStatus.current.serviceId,
success: ({ characteristics }) => {
const characteristic = characteristics.find((i) => refStatus.current.characteristicRule.test(i.uuid))
const characteristic = characteristics.find(i => refStatus.current.characteristicRule.test(i.uuid))
if (!characteristic) {
reject(new Error('特征不可用'))
} else {
}
else {
changeStatus({ characteristicId: characteristic.uuid })
resolve(characteristic)
}
@@ -325,14 +332,16 @@ export default (props) => {
if (refStatus.current.command.isComplete) {
if (refStatus.current.command.isValid && refStatus.current.responseResolve) {
refStatus.current.responseResolve(refStatus.current.command.response)
} else if (!refStatus.current.command.isValid) {
}
else if (!refStatus.current.command.isValid) {
refStatus.current.responseReject(new Error('无效数据'))
}
resetCommand()
}
} else {
}
else {
const uint8Array = new Uint8Array(buffer)
if (uint8Array[0] === 0xbb && uint8Array[1] === 1 && uint8Array[3] === 0) {
if (uint8Array[0] === 0xBB && uint8Array[1] === 1 && uint8Array[3] === 0) {
const ev = { type: 'measure', detail: { mode: uint8Array[2] } }
emit(ev)
}
@@ -345,10 +354,11 @@ export default (props) => {
* @returns {Promise<Uint8Array>}
*/
function exec(command) {
return new Promise(async (resolve, reject) => {
return new Promise(async(resolve, reject) => {
if (refStatus.current.command) {
reject(new Error('正在执行其他命令'))
} else {
}
else {
try {
refStatus.current.command = command
const data = command.data
@@ -359,7 +369,8 @@ export default (props) => {
if (command.responseSize <= 0) {
resolve(true)
resetCommand()
} else {
}
else {
refStatus.current.responseReject = reject
refStatus.current.responseResolve = resolve
refStatus.current.responseTimer = setTimeout(() => {
@@ -367,7 +378,8 @@ export default (props) => {
resetCommand()
}, command.timeout)
}
} catch (e) {
}
catch (e) {
reject(e)
}
}
@@ -471,7 +483,8 @@ export const useBluetooth = () => {
const res = React.useContext<any>(Context)
if (res) {
return { ...res }
} else {
}
else {
return {}
}
}
+11 -8
View File
@@ -1,6 +1,6 @@
import { alert } from '@/common/common'
import Taro from '@tarojs/taro'
import { memo, useCallback, useState } from 'react'
import { alert } from '@/common/common'
type Scope =
| 'scope.userLocation'
@@ -16,21 +16,22 @@ type Scope =
| 'scope.invoiceTitle'
| 'scope.invoice'
| 'scope.userInfo'
type Param = {
interface Param {
scope: Scope
msg: string //检查不通过时警告
msg: string // 检查不通过时警告
}
export default ({ scope, msg }: Param) => {
//这个hook微信授权检查授权
// 这个hook微信授权检查授权
const check = useCallback(() => {
return new Promise((reslove, reject) => {
Taro.getSetting({
success: (res) => {
if (res.authSetting[scope]) {
reslove(true)
} else if (res.authSetting[scope] === undefined) {
}
else if (res.authSetting[scope] === undefined) {
Taro.authorize({
scope: scope,
scope,
success() {
reslove(true)
},
@@ -39,12 +40,14 @@ export default ({ scope, msg }: Param) => {
reject(false)
},
})
} else {
}
else {
Taro.openSetting({
success(res) {
if (res.authSetting[scope]) {
reslove(true)
} else {
}
else {
alert.none(msg)
reject(false)
}
+25 -24
View File
@@ -1,9 +1,10 @@
import { useSelector } from '@/reducers/hooks'
import { useRouter } from '@tarojs/taro'
import dayjs from 'dayjs'
import { useEffect, useRef, useState, SetStateAction, useMemo, useCallback } from 'react'
import type { SetStateAction } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useSelector } from '@/reducers/hooks'
//倒计时hook
// 倒计时hook
export const useTimeCountDown = () => {
const [showTime, setShowTime] = useState({
DD: '',
@@ -11,7 +12,7 @@ export const useTimeCountDown = () => {
MM: '',
SS: '',
})
const [timeStatus, setTimeStatus] = useState<0 | 1 | 2>(0) //倒计时状体 0:倒计时未开始 1:倒计时中, 2:倒计时已结束
const [timeStatus, setTimeStatus] = useState<0 | 1 | 2>(0) // 倒计时状体 0:倒计时未开始 1:倒计时中, 2:倒计时已结束
const timeObj: any = useRef()
const endTime = useRef('')
const onStart = (val = '') => {
@@ -30,8 +31,8 @@ export const useTimeCountDown = () => {
}
}, [])
const count_down = () => {
var startData = dayjs()
var endDate = dayjs(endTime.current)
const startData = dayjs()
const endDate = dayjs(endTime.current)
setTimeStatus(() => 1)
if (startData >= endDate) {
clearInterval(timeObj.current)
@@ -39,19 +40,19 @@ export const useTimeCountDown = () => {
setTimeStatus(() => 2)
return false
}
var _dd = endDate.diff(startData, 'day')
var _hh = endDate.diff(startData, 'hour')
var _mm = endDate.diff(startData, 'minute')
var _ss = endDate.diff(startData, 'second')
const _dd = endDate.diff(startData, 'day')
const _hh = endDate.diff(startData, 'hour')
const _mm = endDate.diff(startData, 'minute')
const _ss = endDate.diff(startData, 'second')
// 转换
var hh = _hh - _dd * 24
var mm = _mm - _hh * 60
var ss = _ss - _mm * 60
const hh = _hh - _dd * 24
const mm = _mm - _hh * 60
const ss = _ss - _mm * 60
// 格式化
var DD = ('00' + _dd).slice(-2)
var HH = ('00' + hh).slice(-2)
var MM = ('00' + mm).slice(-2)
var SS = ('00' + ss).slice(-2)
const DD = (`00${_dd}`).slice(-2)
const HH = (`00${hh}`).slice(-2)
const MM = (`00${mm}`).slice(-2)
const SS = (`00${ss}`).slice(-2)
// console.log('endTime::', `${DD}-${HH}-${MM}-${SS}`)
setShowTime(e => ({ ...e, DD, HH, MM, SS }))
}
@@ -62,7 +63,7 @@ export const useTimeCountDown = () => {
}
}
//订阅消息hook
// 订阅消息hook
// export const UseSubscriptionMessage = () => {
// const { fetchData: fetchDataMessage } = SubscriptionMessageApi()
// const openSubscriptionMessage = ({ orderId = 0, scenes = 0 }: { orderId?: number; scenes: number }) => {
@@ -90,7 +91,7 @@ export const useTimeCountDown = () => {
// }
type NormalPropsType = Record<string | symbol | number, any>
type Options = {
interface Options {
deep?: boolean
}
@@ -115,7 +116,7 @@ export const useNeedMemoCallback = (options: Options = defaultOptions) => {
// 循环props对象
const handleDiff = () => {
for (let [key, value] of Object.entries(prevProps)) {
for (const [key, value] of Object.entries(prevProps)) {
if (!Object.is(value, nextProps[key])) {
// console.log('函数不相等',value === nextProps[key])
// console.log('asdfasdf',value)
@@ -150,7 +151,7 @@ export const useNeedMemoCallback = (options: Options = defaultOptions) => {
}
}
type UsePropsValueOptions<T> = {
interface UsePropsValueOptions<T> {
value?: T
defaultValue: T
onChange?: (v: T) => void
@@ -166,10 +167,10 @@ export function usePropsValue<T>(options: UsePropsValueOptions<T>) {
stateRef.current = value
}
const setState = useCallback((v: SetStateAction<T>, forceTrigger: boolean = false) => {
const setState = useCallback((v: SetStateAction<T>, forceTrigger = false) => {
// `forceTrigger` 意思是 触发 `onChange` 不管 `v` 是否和 `stateRef.current` 相等
const nextValue = typeof v === 'function' ? (v as (prevState: T) => T)(stateRef.current) : v
if (!forceTrigger && nextValue === stateRef.current) return
if (!forceTrigger && nextValue === stateRef.current) { return }
stateRef.current = nextValue
setForceUpdate({})
return onChange?.(nextValue)
@@ -179,7 +180,7 @@ export function usePropsValue<T>(options: UsePropsValueOptions<T>) {
// 点击自定义 tab 时触发。
export function useCustomTabItemTap(callback) {
const { selectedId, tabItem } = useSelector(state => {
const { selectedId, tabItem } = useSelector((state) => {
return state.tabBarData
})
const targetPagePayload = tabItem?.find(item => item.id === selectedId)
+8 -7
View File
@@ -1,11 +1,12 @@
import { useDispatch } from 'react-redux'
import { SET_SHOPCOUNT, CLEAR_SHOPCOUNT } from '@/constants/common'
import { DataParam } from '@/reducers/commonData'
import { useCallback, useState } from 'react'
import { CLEAR_SHOPCOUNT, SET_SHOPCOUNT } from '@/constants/common'
import { DataParam } from '@/reducers/commonData'
// import { GetShoppingCartApi } from '@/api/shopCart'
import { useSelector } from '@/reducers/hooks'
import { useSelector } from '@/reducers/hooks'
export default () => {
const commonData = useSelector((state) => state.commonData)
const commonData = useSelector(state => state.commonData)
const dispatch = useDispatch()
const setShopCount = (shopCount: number) => {
@@ -17,10 +18,10 @@ export default () => {
}
// const { fetchData: fetchDataShopCount } = GetShoppingCartApi()
const getShopCount = async () => {
//获取购物车数据数量
const getShopCount = async() => {
// 获取购物车数据数量
// const { data } = await fetchDataShopCount()
let color_list = data.color_list || []
const color_list = data.color_list || []
setShopCount(color_list.length)
}
+24 -21
View File
@@ -1,12 +1,12 @@
import Taro, { useRouter } from '@tarojs/taro'
import { useEffect, useRef, useState } from 'react'
import { BASE_URL, WX_APPID } from '@/common/constant'
import useUserInfo from './useUserInfo'
import qs from 'qs'
import useUserInfo from './useUserInfo'
import useLogin from './useLogin'
import useLoginRequest from './useLoginRequest'
import { BASE_URL, WX_APPID } from '@/common/constant'
type Params = {
interface Params {
code: string | null
success: boolean
data: any
@@ -23,8 +23,8 @@ type Params = {
page?: number
pageSize?: number
}
type OptionData = Record<string,any> | any[] | null
type option = {
type OptionData = Record<string, any> | any[] | null
interface option {
url?: string
method?: 'get' | 'post' | 'put' | 'delete'
type?: string
@@ -101,11 +101,11 @@ export const useRequest = (
pageSize: 24,
pagination: false, // 是否分页
base_url: '',
apiMsgStatus: true, //是否直接弹出后端错误
apiMsgStatus: true, // 是否直接弹出后端错误
},
) => {
options.url = `${options.base_url || BASE_URL}${options.url}`
let params: Params = {
const params: Params = {
code: null, // 业务码
success: false, // 请求是否成功
data: {},
@@ -129,9 +129,9 @@ export const useRequest = (
const { login } = useLoginRequest()
// 请求函数
const fetchData = async (sub_options?: any) => {
const fetchData = async(sub_options?: any) => {
stateRef.current.loading = true
setState((e) => ({ ...e, loading: true }))
setState(e => ({ ...e, loading: true }))
stateRef.current.query = {
...sub_options,
...(options.pagination && {
@@ -142,7 +142,7 @@ export const useRequest = (
...stateRef.current.sort,
}
try {
let token = Taro.getStorageSync('token')
const token = Taro.getStorageSync('token')
const q = {
...options,
...{
@@ -154,30 +154,31 @@ export const useRequest = (
},
...(options.method?.toUpperCase() == 'GET'
? {
data: stateRef.current.query,
}
data: stateRef.current.query,
}
: {
data: options.type?.toUpperCase() == 'FORMDATA' ? qs.stringify(stateRef.current.query) : stateRef.current.query,
}),
data: options.type?.toUpperCase() == 'FORMDATA' ? qs.stringify(stateRef.current.query) : stateRef.current.query,
}),
}
const result = await Taro.request(q as any)
const { statusCode } = result
const { code, msg, data } = result.data
if (statusCode === 200) {
stateRef.current.success = code === 0 ? true : false
stateRef.current.success = code === 0
stateRef.current.code = code
stateRef.current.msg = msg
stateRef.current.data = data
stateRef.current.total = data?.list ? data?.total : 0
if (code !== 0) {
options.apiMsgStatus !== false &&
Taro.showToast({
options.apiMsgStatus !== false
&& Taro.showToast({
title: `${msg}`,
icon: 'none',
})
console.log('错误::', msg)
}
} else {
}
else {
if (statusCode === 401) {
removeToken()
// removeSessionKey()
@@ -196,14 +197,16 @@ export const useRequest = (
// })
// }
// })
} else {
}
else {
Taro.showToast({
title: `错误:${showStatus(statusCode)}`,
icon: 'none',
})
}
}
} catch (e) {
}
catch (e) {
stateRef.current.success = false
stateRef.current.error = true
stateRef.current.msg = e.errMsg
@@ -211,7 +214,7 @@ export const useRequest = (
}
stateRef.current.error = false
stateRef.current.loading = false
setState(() => ({...stateRef.current}))
setState(() => ({ ...stateRef.current }))
return stateRef.current
}
return {
+26 -22
View File
@@ -1,7 +1,7 @@
import useUserInfo from './useUserInfo'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { GetWxUserInfoApi, GetAdminUserInfoApi, GetPhoneNumberApi, BindingCompanyApi } from '@/api/user'
import useUserInfo from './useUserInfo'
import useLoginRequest from './useLoginRequest'
import { BindingCompanyApi, GetAdminUserInfoApi, GetPhoneNumberApi, GetWxUserInfoApi } from '@/api/user'
import { SHARE_SCENE } from '@/common/enum'
import { GetShortCodeApi } from '@/api/share'
import { alert } from '@/common/common'
@@ -15,34 +15,36 @@ export default () => {
checkLogin()
})
//登录请求
// 登录请求
const { login } = useLoginRequest()
// const {fetchData:login} = LoginApi()
const wxLogin = async () => {
const wxLogin = async() => {
try {
await login()
getAdminUserInfo()
} catch (e) {
}
catch (e) {
console.log('登录失败::', e)
}
}
//获取用户信息
// 获取用户信息
const { fetchData: useFetchData } = GetAdminUserInfoApi()
const getAdminUserInfo = async () => {
let res = await useFetchData()
const getAdminUserInfo = async() => {
const res = await useFetchData()
setAdminUserInfo({ ...res.data })
getShortCode(res.data.user_id)
}
//登录加checkLogin检查
// 登录加checkLogin检查
const checkLogin = () => {
return new Promise(async (reslove) => {
return new Promise(async(reslove) => {
if (!userInfo.token) {
await wxLogin()
reslove(true)
} else {
//这个东西不要打开,checkSession有调用频率问题
}
else {
// 这个东西不要打开,checkSession有调用频率问题
// Taro.checkSession({
// success: async () => {
// reslove(true)
@@ -57,9 +59,9 @@ export default () => {
})
}
//获取用户头像等信息数据
// 获取用户头像等信息数据
const { fetchData: fetchDataUserInfo } = GetWxUserInfoApi()
const getSelfUserInfo = async () => {
const getSelfUserInfo = async() => {
return new Promise((reslove, reject) => {
if (userInfo.adminUserInfo?.is_authorize_name) {
reslove(true)
@@ -67,7 +69,7 @@ export default () => {
}
Taro.getUserProfile({
desc: '用于完善会员资料',
success: async (res) => {
success: async(res) => {
if (!userInfo.session_key) {
await wxLogin()
}
@@ -82,7 +84,8 @@ export default () => {
setUserInfo({ ...user_res.data })
getAdminUserInfo()
reslove(true)
} else {
}
else {
reject(user_res.msg)
}
},
@@ -94,11 +97,11 @@ export default () => {
})
}
//获取手机号码
// 获取手机号码
const { fetchData: fetchDataUserPhone } = GetPhoneNumberApi()
const { fetchData: fetchBindingCompany } = BindingCompanyApi()
const getPhoneNumber = (code) => {
return new Promise(async (reslove, reject) => {
return new Promise(async(reslove, reject) => {
if (userInfo.adminUserInfo?.is_authorize_phone) {
reslove(true)
return true
@@ -109,18 +112,19 @@ export default () => {
await fetchBindingCompany()
getAdminUserInfo()
reslove(res.data)
} else {
}
else {
reject(res.msg)
}
})
}
//获取分享码(右上角分享码)
// 获取分享码(右上角分享码)
const { SharePage } = SHARE_SCENE
const { fetchData: fetchDataShortCode } = GetShortCodeApi()
const getShortCode = async (user_id) => {
const getShortCode = async(user_id) => {
const { data: resPage } = await fetchDataShortCode({ share_user_id: user_id, type: SharePage.value })
setSortCode({ ...userInfo.sort_code, shareShortPage: { title: '打造面料爆品 专注客户服务', code: resPage.md5_key, img: IMG_CND_Prefix + '/mall/share_img_01.png' } })
setSortCode({ ...userInfo.sort_code, shareShortPage: { title: '打造面料爆品 专注客户服务', code: resPage.md5_key, img: `${IMG_CND_Prefix}/mall/share_img_01.png` } })
}
return {
+34 -27
View File
@@ -1,28 +1,29 @@
import { BASE_URL, WX_APPID } from '@/common/constant'
import Taro, { useRouter } from '@tarojs/taro'
import { useRef } from 'react'
import qs from 'qs'
import useUserInfo from './useUserInfo'
// eslint-disable-next-line import/first
import { BASE_URL, WX_APPID } from '@/common/constant'
//开这个hook 主要是为了让useHttp 能够调用
// 开这个hook 主要是为了让useHttp 能够调用
type Param = { success: boolean; data: any; msg: string; code: null | number; loading: boolean }
let loginStatus = false //登录状态,true登录中
interface Param { success: boolean; data: any; msg: string; code: null | number; loading: boolean }
let loginStatus = false // 登录状态,true登录中
export default () => {
let initData = {
const initData = {
success: false,
data: null,
msg: '',
code: null,
loading: false,
}
let loginData = useRef<Param>(initData)
const loginData = useRef<Param>(initData)
const { setToken, setSessionKey } = useUserInfo()
const router = useRouter()
//微信登录请求v2
const fetchDataLogin = async (login_code) => {
// 微信登录请求v2
const fetchDataLogin = async(login_code) => {
const q = {
url: BASE_URL + '/v2/mp/login',
url: `${BASE_URL}/v2/mp/login`,
header: {
Platform: 3,
Appid: WX_APPID,
@@ -35,20 +36,22 @@ export default () => {
const result = await Taro.request(q as any)
const { code, data, msg } = result.data
if (result.statusCode === 200) {
loginData.current.success = code === 0 ? true : false
loginData.current.success = code === 0
loginData.current.code = code
loginData.current.msg = msg
loginData.current.data = data
} else {
}
else {
Taro.showToast({
title: `错误:登录失败`,
title: '错误:登录失败',
icon: 'none',
})
console.log('登录错误:', result.errMsg)
}
} catch (e) {
}
catch (e) {
Taro.showToast({
title: `错误:登录失败`,
title: '错误:登录失败',
icon: 'none',
})
console.log('登录错误:', e.errMsg)
@@ -56,44 +59,48 @@ export default () => {
return loginData.current
}
//微信登录
// 微信登录
const login = () => {
return new Promise((resolve, reject) => {
if (loginStatus) return reject(false)
// eslint-disable-next-line prefer-promise-reject-errors
if (loginStatus) { return reject(false) }
loginStatus = true
Taro.login({
success: async (res) => {
success: async(res) => {
if (res.code) {
const { data, success, msg } = await fetchDataLogin(res.code)
if (success) {
setToken(data.token)
setSessionKey(data.session_key)
resolve(data)
let params = router.params
const params = router.params
delete params.$taroTimestamp
if (router.path === '/pages/index/index' || router.path === '/pages/user/index') {
Taro.reLaunch({
url: router.path + '?' + qs.stringify(params),
})
} else {
Taro.redirectTo({
url: router.path + '?' + qs.stringify(params),
url: `${router.path}?${qs.stringify(params)}`,
})
}
} else {
else {
Taro.redirectTo({
url: `${router.path}?${qs.stringify(params)}`,
})
}
}
else {
Taro.showToast({
title: '登录失败',
icon: 'none',
})
reject(msg)
}
} else {
console.log('登录失败!' + res.errMsg)
}
else {
console.log(`登录失败!${res.errMsg}`)
reject(res.errMsg)
}
loginStatus = false
},
fail: function (e) {
fail(e) {
console.log('登录失败!::', e)
reject(e)
loginStatus = false
+52 -42
View File
@@ -3,7 +3,7 @@ import { UPLOAD_CDN_URL } from '@/common/constant'
import { GetSignApi } from '@/api/cdn'
export default () => {
const { fetchData: GetSign, state } = GetSignApi()
const { fetchData: GetSign } = GetSignApi()
// 上传图片 获取auth,Policy
/*
@@ -11,18 +11,21 @@ export default () => {
type 类型值,区分上传业务bucket
*/
const getSecret = (scene, type) => {
return new Promise(async (resolve, reject) => {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async(resolve, reject) => {
const SAVE_PATH = `/${scene}/{filemd5}{day}{hour}{min}{sec}{.suffix}`
let params = {
const params = {
method: 'post',
save_key: SAVE_PATH,
}
// 获取签名
let res = await GetSign(params)
const res = await GetSign(params)
if (res.success) {
resolve(res.data)
} else {
}
else {
// eslint-disable-next-line prefer-promise-reject-errors
reject({
code: res.code || '9999',
msg: res.msg,
@@ -31,15 +34,17 @@ export default () => {
})
}
const getFileType = (name) => {
if (!name) return false
var imgType = ['gif', 'jpeg', 'jpg', 'bmp', 'png']
var videoType = ['avi', 'wmv', 'mkv', 'mp4', 'mov', 'rm', '3gp', 'flv', 'mpg', 'rmvb', 'quicktime']
if (!name) { return false }
const imgType = ['gif', 'jpeg', 'jpg', 'bmp', 'png']
const videoType = ['avi', 'wmv', 'mkv', 'mp4', 'mov', 'rm', '3gp', 'flv', 'mpg', 'rmvb', 'quicktime']
if (RegExp('.?(' + imgType.join('|') + ')$', 'i').test(name.toLowerCase())) {
if (RegExp(`.?(${imgType.join('|')})$`, 'i').test(name.toLowerCase())) {
return 'image'
} else if (RegExp('.(' + videoType.join('|') + ')$', 'i').test(name.toLowerCase())) {
}
else if (RegExp(`.(${videoType.join('|')})$`, 'i').test(name.toLowerCase())) {
return 'video'
} else {
}
else {
return false
}
}
@@ -52,7 +57,7 @@ export default () => {
* @returns
*/
const uploadCDNImg = (file, secene, type) => {
let filetype = file.path
const filetype = file.path
console.log('filetype::', filetype)
if (!getFileType(filetype)) {
Taro.showToast({
@@ -66,9 +71,9 @@ export default () => {
return new Promise<Record<string, any>>((resolve, reject) => {
getSecret(secene, type)
.then((result) => {
let res: any = result
const res: any = result
console.log('bucket', res.bucket)
var formdata = {
const formdata = {
authorization: res.authorization,
policy: res.policy,
}
@@ -93,7 +98,8 @@ export default () => {
Taro.showLoading({
title: '上传中...',
})
} else {
}
else {
Taro.hideLoading()
}
})
@@ -109,10 +115,10 @@ export default () => {
})
}
// product 产品相关,图片、纹理图等 全平台
// after-sale 售后(申请退货、退款)相关的、图片、视频 全平台
// mall 电子商城相关的 全平台
// logistics 物流(发货、提货)相关的、图片、视频 全平台
// product 产品相关,图片、纹理图等 全平台
// after-sale 售后(申请退货、退款)相关的、图片、视频 全平台
// mall 电子商城相关的 全平台
// logistics 物流(发货、提货)相关的、图片、视频 全平台
type cdn_upload_type_Param = 'product' | 'after-sale' | 'mall' | 'logistics'
/**
* 上传手机图片
@@ -120,27 +126,29 @@ export default () => {
* @param count // 1时返回一张图片信息, 大于1时返回图片数组
* @returns
*/
const getWxPhoto = (cdn_upload_type: cdn_upload_type_Param, count: number = 1) => {
const getWxPhoto = (cdn_upload_type: cdn_upload_type_Param, count = 1) => {
return new Promise((resolve, reject) => {
let list: any[] = []
const list: any[] = []
Taro.chooseImage({
count: count,
count,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: async function (res) {
async success(res) {
try {
if (count > 1) {
for (let i = 0; i < res.tempFiles.length; i++) {
let data = await uploadCDNImg(res.tempFiles[i], cdn_upload_type, cdn_upload_type)
const data = await uploadCDNImg(res.tempFiles[i], cdn_upload_type, cdn_upload_type)
list.push(data)
}
resolve(list)
} else {
//兼容以前上传一张的情况
let data = await uploadCDNImg(res.tempFiles[0], cdn_upload_type, cdn_upload_type)
}
else {
// 兼容以前上传一张的情况
const data = await uploadCDNImg(res.tempFiles[0], cdn_upload_type, cdn_upload_type)
resolve(data)
}
} catch (res) {
}
catch (res) {
reject(res)
}
},
@@ -148,36 +156,38 @@ export default () => {
})
}
// product 产品相关,图片、纹理图等 全平台
// after-sale 售后(申请退货、退款)相关的、图片、视频 全平台
// mall 电子商城相关的 全平台
// logistics 物流(发货、提货)相关的、图片、视频 全平台
// product 产品相关,图片、纹理图等 全平台
// after-sale 售后(申请退货、退款)相关的、图片、视频 全平台
// mall 电子商城相关的 全平台
// logistics 物流(发货、提货)相关的、图片、视频 全平台
/**
* 上传聊天记录图片
* @param cdn_upload_type 场景值
* @param count // 1时返回一张图片信息, 大于1时返回图片数组
* @returns
*/
const getChatPhoto = (cdn_upload_type: cdn_upload_type_Param, count: number = 1) => {
const getChatPhoto = (cdn_upload_type: cdn_upload_type_Param, count = 1) => {
return new Promise((resolve, reject) => {
let list: any[] = []
const list: any[] = []
Taro.chooseMessageFile({
count: count,
count,
type: 'image',
success: async function (res) {
async success(res) {
try {
if (count > 1) {
for (let i = 0; i < res.tempFiles.length; i++) {
let data = await uploadCDNImg(res.tempFiles[i], cdn_upload_type, cdn_upload_type)
const data = await uploadCDNImg(res.tempFiles[i], cdn_upload_type, cdn_upload_type)
list.push(data)
}
resolve(list)
} else {
//兼容以前上传一张的情况
let data = await uploadCDNImg(res.tempFiles[0], cdn_upload_type, cdn_upload_type)
}
else {
// 兼容以前上传一张的情况
const data = await uploadCDNImg(res.tempFiles[0], cdn_upload_type, cdn_upload_type)
resolve(data)
}
} catch (res) {
}
catch (res) {
reject(res)
}
},
@@ -188,6 +198,6 @@ export default () => {
return {
uploadCDNImg,
getWxPhoto,
getChatPhoto
getChatPhoto,
}
}
+12 -11
View File
@@ -1,34 +1,35 @@
import { useDispatch } from 'react-redux'
import type { Dispatch } from 'redux'
import { UserInfoActionType } from '@/constants/userInfo'
import { DataParam, UserParam, UserAdminParam, SortCodeParam, UserInfoAction } from '@/reducers/userInfo'
import { Dispatch } from 'redux'
import type { SortCodeParam, UserAdminParam, UserInfoAction, UserParam } from '@/reducers/userInfo'
import { useSelector } from '@/reducers/hooks'
export default () => {
const userInfo = useSelector((state) => state.userInfoData)
const userInfo = useSelector(state => state.userInfoData)
const dispatch = useDispatch<Dispatch<UserInfoAction>>()
const setToken = (token: string) => {
// @ts-ignore
// @ts-expect-error data 类型没有约束好
dispatch({ type: UserInfoActionType.SET_TOKEN, data: { token } })
}
const setSessionKey = (sessionkey: string) => {
// @ts-ignore
// @ts-expect-error data 类型没有约束好
dispatch({ type: UserInfoActionType.SET_SESSIONKEY, data: { session_key: sessionkey } })
}
const setUserInfo = (userInfo: UserParam) => {
// @ts-ignore
dispatch({ type: UserInfoActionType.SET_USERINFO, data: { userInfo } })
const setUserInfo = (userInfoProp: UserParam) => {
// @ts-expect-error data 类型没有约束好
dispatch({ type: UserInfoActionType.SET_USERINFO, data: { userInfoProp } })
}
const setAdminUserInfo = (adminUserInfo: UserAdminParam) => {
// @ts-ignore
// @ts-expect-error data 类型没有约束好
dispatch({ type: UserInfoActionType.SET_ADMINUSERINFO, data: { adminUserInfo } })
}
const setSortCode = (sortCode: SortCodeParam) => {
// @ts-ignore
// @ts-expect-error data 类型没有约束好
dispatch({ type: UserInfoActionType.SET_SORTCODE, data: { sort_code: sortCode } })
}
@@ -53,6 +54,6 @@ export default () => {
removeToken,
removeSessionKey,
setSortCode,
userInfo, //响应式数据返回
userInfo, // 响应式数据返回
}
}