【问题标题】:why i'm a getting NaN为什么我会越来越 NaN
【发布时间】: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


    【解决方案1】:

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

    { count: initialCount }
    

    【讨论】:

      【解决方案2】:

      这很简单,您只需更新您的 { initialCount: initialCount } 以获取值。

      它应该看起来像这样 { count: initialCount }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-18
        • 2021-08-28
        • 1970-01-01
        相关资源
        最近更新 更多