【发布时间】:2021-09-14 12:24:06
【问题描述】:
我有一个简单的 useReducer 增量计数器。
import {useReducer} from 'react'
const counterStateFn = (state,action) => {
if(action.type === "INCREMENT") {
return {count : state.count++}
}
if(action.type === "DECREMENT") {
return {count : state.count--}
}
return {count: 0}
}
const Counter = () => {
const [counterState, modifierCounterState] = useReducer(counterStateFn,{count: 0});
const modifierCounterStateIncrementFn = () => {
modifierCounterState({type:"INCREMENT"});
}
const modifierCounterStateDecrementFn = () => {
modifierCounterState({type:"DECREMENT"})
}
return (
<div className="counter-wrap">
<button onClick={modifierCounterStateIncrementFn}>Increment(+)</button>
<span>Count is: {counterState.count}</span>
<button onClick={modifierCounterStateDecrementFn}>Decrement(-)</button>
</div>
);
}
export default Counter;
在counterStateFn 内部,我使用{count : state.count++} 和{count : state.count--} 来递增和递减计数器,但这不起作用。
如果我使用{count : ++state.count} 或{count : state.count+1},它将起作用。
我想知道为什么{count : state.count++} 和{count : state.count--} 不起作用。
谢谢。
【问题讨论】:
标签: javascript reactjs increment use-reducer