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

React-Redux-Saga计数器项目reducer获取action.payload.step为undefined怎么办

问题核心

你的step参数是挂载在INCREMENT_REQUEST/DECREMENT_REQUEST类型的action上的,但实际修改count值的逻辑在reducer的INCREMENT_SUCCESS/DECREMENT_SUCCESS分支,而你saga触发SUCCESS类型action时没有携带step参数,导致reducer拿不到对应数值。


修改方案

1. 修改Sagas代码

接收takeEvery传递过来的原始request action,提取step参数,在触发success action时携带对应数值:

// 引入常量避免拼写错误
import { 
  INCREMENT_REQUEST, 
  INCREMENT_SUCCESS, 
  DECREMENT_REQUEST, 
  DECREMENT_SUCCESS 
} from "./actionTypes";
import { takeEvery, call, put } from "redux-saga/effects";

const delay = (ms) => new Promise((res) => setTimeout(res, ms));

// 接收原始action作为参数
function* incrementAsync(action) {
  yield call(delay, 2000);
  // put时携带step参数
  yield put({ 
    type: INCREMENT_SUCCESS,
    payload: { step: action.payload.step }
  });
}

export function* watchIncrement() {
  yield takeEvery(INCREMENT_REQUEST, incrementAsync);
}

function* decrementAsync(action) {
  yield call(delay, 2000);
  yield put({ 
    type: DECREMENT_SUCCESS,
    payload: { step: action.payload.step }
  });
}

export function* watchDecrement() {
  yield takeEvery(DECREMENT_REQUEST, decrementAsync);
}

2. 修改Reducer代码

把SUCCESS分支里硬编码的加减1改成读取action里的step参数:

import {
  INCREMENT_REQUEST,
  INCREMENT_SUCCESS,
  INCREMENT_FAILURE,
  DECREMENT_REQUEST,
  DECREMENT_SUCCESS,
  DECREMENT_FAILURE,
} from "../actions/actionTypes";

const initialState = {
  value: 0,
  loading: null,
  error: null,
};

const counterReducers = (state = initialState, action) => {
  switch (action.type) {
    case INCREMENT_REQUEST:
      return { ...state, loading: true, error: null };
    case INCREMENT_SUCCESS:
      return {
        ...state,
        value: state.value + action.payload.step,
        loading: false,
        error: null,
      };
    case INCREMENT_FAILURE:
      return { ...state, error: action.error };
    case DECREMENT_REQUEST:
      return { ...state, loading: true, error: null };
    case DECREMENT_SUCCESS:
      return {
        ...state,
        value: state.value - action.payload.step,
        loading: false,
        error: null,
      };
    case DECREMENT_FAILURE:
      return { ...state, error: action.error };

    default:
      return state;
  }
};

export default counterReducers;

修改完成后即可动态传入step值,比如需要新增+5的按钮,直接调用dispatch(incrementAction(5))即可正常生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:30:00