【问题标题】:ReactJS incrementor++ not working inside useReducerReactJS incrementor++ 在 useReducer 中不起作用
【发布时间】: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


    【解决方案1】:

    正如 Dennis x++ 运算符所指出的,返回值然后递增。

    要解决您的问题,您可以使用 ++count 或 count + 1。

    const counterStateFn =  (state,action) => {
     if(action.type === "INCREMENT") {
         return {count : state.count + 1}
     }
     if(action.type === "DECREMENT") {
        return {count : state.count - 1}
    }
     return {count: 0}
    }
    

    【讨论】:

      【解决方案2】:

      如其文档中所述,Increment (++) operator,如果用作后缀,它会递增并返回值在递增之前

      虽然您希望值 AFTER 递增以触发状态更改。

      您可以在 Devtools 中自行查看:

      x = 5;
      x++ // returns 5
      
      y = 5;
      ++y // returns 6
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 1970-01-01
        • 1970-01-01
        • 2023-02-03
        • 1970-01-01
        • 2017-06-03
        • 2021-04-12
        相关资源
        最近更新 更多