2017-12-02 38 views
1

我尝试更新我的状态时添加一个项目在数组中,使用react/redux和REDEX传奇中间件。但是,在我这样做的地方,我有一个数组,其中每个项目都有一个索引(0,1,2 ....),但是当我添加新项目(名为step)时,新项目没有索引,但它是这样的:添加与索引数组中的项目 - 反应REDX和REDX传奇

[ 
    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 }); 
} 

如果有人应该帮忙,

谢谢!

+1

[_.merge](https://lodash.com/docs/4.17 .4#合并)与对象不是数组一起工作 –

回答

1

看来你在用lodash,注意_.mergeworks with objects not arrays

如果你只是想要一个新的项目添加到一个数组的END可以使用ES2015 spread feature

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

如果我使用这个,我没有索引,但'[step:NewItem]' –

+0

这是不可能的,因为数组没有键。和'nextState'根据我的例子是一个数组。 –

+0

感谢你,对'_.merge'来说,现在它工作的很好! –