【发布时间】:2021-09-09 11:48:44
【问题描述】:
我尝试了这种在减速器函数中包含调度功能的模式,但是无论我尝试增加或减少什么,我都得到了这个 NaN是最好的方法,但至少我尝试了不同的方法,我缺少什么问题才能使它起作用[原谅我的英语]
import * as React from 'react';
const CounterContext = React.createContext();
function CounterProvider({ step = 1, initialCount = 0, ...props }) {
const [state, dispatch] = React.useReducer(
(state, action) => {
const change = action.step ?? step
switch (action.type) {
case 'increment': {
return { ...state, count: state.count + change }
}
case 'decrement': {
return { ...state, count: state.count - change }
}
default: {
throw new Error(`Unhandled action type:${action.type}`)
}
}
},
{ initialCount: initialCount })
const increment = React.useCallback(() => dispatch({ type: 'increment' }), [
dispatch
])
const decrement = React.useCallback(() => dispatch({ type: 'decrement' }), [
dispatch
])
const value = { increment, decrement, state }
return <CounterContext.Provider value={value} {...props} />
}
function useCounter() {
const context = React.useContext(CounterContext)
if (context === undefined) {
throw new Error('useCounter must be used within CounterProvider')
}
return context
}
function Counter() {
const { state, increment, decrement } = useCounter();
console.log(state, 'inc ', increment, 'dec ', decrement)
return (
<div>
<button onClick={decrement}>-</button>
<button onClick={increment}>+</button>
<div>Current Count: {state.count}</div>
</div>
)
}
function App() {
return (
<CounterProvider>
<Counter />
</CounterProvider>
)
}
export default App
【问题讨论】:
标签: javascript reactjs use-reducer