✨ feat(购物车): 使用context解决跨层级问题
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user