我在使用react / redux和redux-saga中间件添加数组中的项目时尝试更新我的状态。但是在我这样做的地方,我有一个数组,每个项目都有一个索引(0,1,2 ......)但是当我添加新项目(命名为步骤)时,新项目没有索引但是它就像:
[
0: item1,
1: item2,
2: item3,
step: newItem
]
我希望新项目有一个索引like 3: newItem
这是减速器:
export function stepReducer(state = [], action) {
switch (action.type) {
case Actions.CREATE_STEP_REQUEST:
return state;
case Actions.STEP_CREATED:
let newArray = action.steps.slice();
newArray.splice(action.index, 0, action.step);
return newArray;
case Actions.FETCH_TRAVEL_STEPS_REQUIRED:
return state;
case Actions.TRAVEL_STEPS_DATA_SUCCESS:
let updatedSteps = _.merge(action.steps, state.steps);
return updatedSteps;
default:
return state;
}
}
和传奇文件:
export function* createStep(action) {
const step = yield call(stepApi.createStep, action.travelId, action.step, action.authToken);
const steps = yield select((state) => state.steps);
const index = steps.length;
yield put({ type: Actions.STEP_CREATED, steps, step, index });
}
如果有人应该帮忙,
谢谢!
答案 0 :(得分:2)
您似乎正在使用lodash
,请注意_.merge
works with objects not arrays。
如果您只想在数组的 END 中添加新项,可以使用ES2015 spread feature:
const nextState = [...state, action.step];