为什么我得到 NaN

why i'm a getting NaN

我尝试了这种在我的 reducer 函数中包含调度功能的模式,但是无论我尝试递增还是递减,我都得到了这个 NaN 我缺少的东西基本上是在我的 reducer 函数中创建辅助方法以获得更好的 api 方法可能不是最好的方法,但至少我尝试了不同的方法,为了让它起作用,我遗漏了什么问题[原谅我的英语]

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

因为你传initial的值是{ initialCount: initialCount }。所以你没有count。只需更新到 count

{ count: initialCount }

很简单,您只需将 { initialCount: initialCount } 更新为计数即可获得值。

它应该是这样的 { count: initialCount }