✨ feat(购物车): 使用context解决跨层级问题

This commit is contained in:
xuan
2022-09-23 15:46:56 +08:00
parent 553445f111
commit b9a0b64826
8 changed files with 225 additions and 146 deletions
+45 -3
View File
@@ -1,15 +1,13 @@
import React from 'react'
import React, { useRef } from 'react'
import { useContext } from 'react'
/**
* 456: {
* id: 456,
* name: 'asdfasf',
* checked: true
* },
* 457: {
* id: 457,
* name: 'dsfaf654',
* checked: true
* }
*/
@@ -21,6 +19,10 @@ export interface ColorMeta {
}
export interface ShoppingContextValue {
isManageStatus: boolean
setManageStatus: (isManageStatus: boolean) => void
currentCheckedPurchaserId: number
setCurrentCheckedPurchaserId: (purchaserId: number) => void
colorStore: ColorStore
setChangedCheckbox: (color: ColorMeta) => void
}
@@ -34,3 +36,43 @@ export function useShoppingContext() {
}
return ctx
}
export function useWatch(id: ColorMeta['id']) {
const { colorStore } = useShoppingContext()
console.log('colorStore==>', colorStore)
return id ? colorStore[id] : colorStore
}
export interface ShoppingCartAction {
setManageStatus: (manageStatus: boolean) => void
getManageStatus: () => boolean
}
export interface InternalShoppingCartAction extends ShoppingCartAction {
__INTERNAL__: React.MutableRefObject<ShoppingCartAction | null>
}
function throwError(): never {
throw new Error('有没有用 ref 这个props?')
}
export function useShoppingCart(): ShoppingCartAction {
const __INTERNAL__ = useRef<ShoppingCartAction | null>(null)
return {
__INTERNAL__,
setManageStatus(manageStatus: boolean) {
const action = __INTERNAL__.current
if (!action) {
throwError()
}
action.setManageStatus(manageStatus)
},
getManageStatus() {
const action = __INTERNAL__.current
if (!action) {
throwError()
}
return action.getManageStatus()
},
} as InternalShoppingCartAction
}