使用索引在数组中添加项目 - react redux 和 redux-saga
Add item in array with index - react redux and redux-saga
我尝试使用 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;
}
}
和 saga 文件:
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 });
}
如果有人需要帮助,
谢谢!
您似乎正在使用 lodash
,请注意 _.merge
works with objects not arrays。
如果您只想将新项目添加到数组的 END 中,您可以使用 ES2015 spread feature:
const nextState = [...state, action.step];
我尝试使用 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;
}
}
和 saga 文件:
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 });
}
如果有人需要帮助,
谢谢!
您似乎正在使用 lodash
,请注意 _.merge
works with objects not arrays。
如果您只想将新项目添加到数组的 END 中,您可以使用 ES2015 spread feature:
const nextState = [...state, action.step];