2017-12-02 4 views
1

react/redux 및 redux-saga 미들웨어를 사용하여 배열에 항목을 추가 할 때 내 상태를 업데이트하려고합니다. 그러나 내가 이것을하는 곳에서는 각 항목에 인덱스 (0, 1, 2 ....)가있는 배열이 있지만 새 항목 (단계라는)을 추가하면 새 항목에 인덱스가 없지만 감속기됩니다인덱스가있는 배열에 항목 추가 - reactx 및 redux-saga

[ 
    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 # merge)는 배열이 아닌 객체와 함께 작동합니다. –

답변

1

lodash으로 작업하는 것 같습니다. _.mergeworks with objects not arrays에 유의하십시오. 그냥 배열의 END에 새 항목을 추가하려면

사용할 수있는 ES2015 spread feature :

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

이것을 사용하면 인덱스가 없지만 배열에 키가 없기 때문에 불가능한'[step : NewItem]' –

+0

입니다. 내 예제에 따라'nextState'는 배열입니다. –

+0

당신은'_.merge'를 위해 당신이 맞아요, 지금은 잘 작동합니다! –