我正在学习redux。我试图通过递增递减值来学习redux。我写了一个代码。当我调度INCREMENT_BY_VALUE
时,它显示NaN
,但INCREMENT
,DECREMENT
和RESET
工作正常。
下面是我的代码:
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 }
为什么会发生这种情况,我该如何解决?
1条答案
按热度按时间jyztefdp1#
您的
incrementByValue
操作创建器返回一个具有action
属性的对象,但在reducer函数中,您正在访问payload
属性,该属性不存在。该属性的计算结果为undefined
,并将其添加到数字中,结果为NaN
。要么更改reducer以使用
action
属性,要么使操作创建器返回一个具有payload
属性的对象。