为什么在redux上获得NaN,同时添加一个数字

nafvub8i  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(78)

我正在学习redux。我试图通过递增递减值来学习redux。我写了一个代码。当我调度INCREMENT_BY_VALUE时,它显示NaN,但INCREMENTDECREMENTRESET工作正常。
下面是我的代码:

const { createStore } = require("redux")

const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
const RESET = 'RESET'
const INCREMENT_BY_VALUE = "INCREMENT_BY_VALUE"

const initialCounterState = {
  count: 0
}

const incrementCounter = () => {
  return {
    type: INCREMENT
  }
}

const decrementCounter = () => {
  return {
    type: DECREMENT
  }
}

const incrementByValue = (value) => {
  return {
    type: INCREMENT_BY_VALUE,
    action: value
  }
}

const resetCounter = () => {
  return {
    type: RESET
  }
}

const counterReducer = (state = initialCounterState, action) => {
  switch (action.type) {
    case INCREMENT:
      return {
        ...state,
        count: state.count + 1
      }

    case DECREMENT:
      return {
        ...state,
        count: state.count - 1
      }

      
    case RESET:
      return {
        ...state,
        count: 0
      }

    case INCREMENT_BY_VALUE:
      return {
        ...state,
        count: state.count + action.payload
      }

    default:
      break;
  }
}

const store = createStore(counterReducer)

store.subscribe(() => {
  console.log(store.getState());
})

store.dispatch(incrementCounter())
store.dispatch(decrementCounter())
store.dispatch(resetCounter())
store.dispatch(incrementByValue(10))

我从我的代码中得到以下输出:

{ count: 1 }
{ count: 0 }
{ count: 0 }
{ count: NaN }

为什么会发生这种情况,我该如何解决?

jyztefdp

jyztefdp1#

您的incrementByValue操作创建器返回一个具有action属性的对象,但在reducer函数中,您正在访问payload属性,该属性不存在。该属性的计算结果为undefined,并将其添加到数字中,结果为NaN
要么更改reducer以使用action属性,要么使操作创建器返回一个具有payload属性的对象。

相关问题