React Native redux reducers best way to push array

一曲冷凌霜 提交于 2019-12-24 03:38:09

问题


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


来源:https://stackoverflow.com/questions/47068926/react-native-redux-reducers-best-way-to-push-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!