React Native redux reducers best way to push array

2019-07-19 07:11发布

问题:

I have the following state and reducer but it's not pushing in the new array object.

const initialState = {
    photos: [],
    selectedPhoto:{},
    photosTeamId:'',
    photosProjectId:''
};

case actionTypes.PHOTOS_UPDATE:
            return Object.assign({}, state, {
                photos:action.data.photos,
                photosTeamId:action.data.photosTeamId,
                photosProjectId:action.data.photosProjectId
            })

photos is not getting pushed but overwritten

回答1:

Here's a more cleaner way using javascript spread syntax:

const initialState = {
    photos: [],
    selectedPhoto:{},
    photosTeamId:'',
    photosProjectId:''
};

case actionTypes.PHOTOS_UPDATE:
            return {
                ...state,
                photos: [...state.photos, ...actions.data.photos],
                photosTeamId: action.data.photosTeamId,
                photosProjectId: action.data.photosProjectId
            }


回答2:

case actionTypes.PHOTOS_UPDATE:
  return {
    ...state,
    photos: state.photos.concat(action.data.photos),
    photosTeamId: action.data.photosTeamId,
    photosProjectId: action.data.photosProjectId
  };


回答3:

Here's the spread operator […]. The spread operator can be used to take an existing array and add another element to it while still preserving the original array.

Example:

case actionTypes.PHOTOS_UPDATE:
  return [
    ...state,
    Object.assign({}, {
      photos:action.data.photos,
      photosTeamId:action.data.photosTeamId,
      photosProjectId:action.data.photosProjectId
    })
  ];