我正在使用在反应项目中here找到的浸入式减水剂包装。
我已经设置了一个上下文提供程序,并希望在该上下文中共享化简操作,以便可以从提供程序中调用它们,例如:
function Counter() {
const dispatch = useCountDispatch()
return (
<button onClick={() => dispatch(increment(1))}>Increment count</button>
)
}
const App = () => (
<CountProvider>
<Counter />
</CountProvider>
)
在示例文档中,通过使用由immer-reducer例如
生成的ActionCreators来调用动作。dispatch(ActionCreators.increment(1));
如何从提供者中传递ActionCreators,以及如何定义Dispatch类型?
import { ImmerReducer, createActionCreators, createReducerFunction } from "immer-reducer"
type Dispatch = (action: ?) => void
type State = { count: number }
type CountProviderProps = { children: React.ReactNode }
const CountStateContext = React.createContext<State | undefined>(undefined)
const CountDispatchContext = React.createContext<Dispatch | undefined>(undefined)
const initialState = { count: 0 }
class ReducerClass extends ImmerReducer<typeof initialState> {
increment(amount: number) {
this.draftState.count = this.draftState.count + amount
}
}
const ActionCreators = createActionCreators(ReducerClass)
const reducerFuntion = createReducerFunction(ReducerClass)
function CountProvider({ children }: CountProviderProps) {
const [state, dispatch] = React.useReducer(reducerFuntion, initialState)
return (
<CountDispatchContext.Provider value={dispatch}>
{children}
</CountDispatchContext.Provider>
)
}
function useCountState() {
const context = React.useContext(CountStateContext)
if (context === undefined) {
throw new Error("")
}
return context
}
function useCountDispatch() {
const context = React.useContext(CountDispatchContext)
if (context === undefined) {
throw new Error("")
}
return context
}
export { CountProvider, useCountState, useCountDispatch }