You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux更新对象state时counter增减功能实现及报错排查

错误原因

  • reducer中更新counter值时,错误直接对整个state对象做加减运算,而非取state里的counter属性运算,导致对象和数字拼接得到异常值,是报错的核心原因
  • reducer的default分支残留了冗余无效的state语句,属于语法冗余

修正后的counterReducer代码

const initialState = {
    counter: 0
}

const counter = (state=initialState,action) => {
    switch(action.type){
        case 'INCREMENT':
            // 取state下的counter属性做加法,不要直接操作整个state对象
            return {...state,counter : state.counter +1}
        case 'DECREMENT':
            // 减操作同理取state.counter计算
            return {...state,counter : state.counter -1}
        default:
            // 删掉多余的state语句
            return state;
    }
}

export default counter;

其余的Action、App.js、Index.js代码无需调整,替换reducer代码即可正常实现加减功能。

内容的提问来源于stack exchange,提问作者Ayaan Abbasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:54:02