【问题标题】:Add item in array with index - react redux and redux-saga使用索引在数组中添加项目 - 反应 redux 和 redux-saga
【发布时间】:2018-05-16 13:25:11
【问题描述】:

我尝试在数组中添加项目时更新我的​​状态,使用 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 });
}

如果有人应该帮忙,

谢谢!

【问题讨论】:

  • _.merge 适用于对象而非数组

标签: arrays reactjs redux redux-saga


【解决方案1】:

您似乎正在使用lodash,请注意_.merge works with objects not arrays

如果您只想在数组的 END 中添加新项目,可以使用 ES2015 spread feature

const nextState = [...state, action.step];

【讨论】:

  • 如果我用这个,我没有索引,但是[step: NewItem]
  • 这是不可能的,因为数组没有键。根据我的示例,nextState 是一个数组。
  • 谢谢你,_.merge 是对的,现在它运行良好!
猜你喜欢
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多