React Native redux reducers 推送数组的最佳方式



我有以下状态和化简器,但它没有推送新的数组对象。

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

照片没有被推送,而是被覆盖

以下是使用javascript扩展语法的更简洁的方法:

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
            }
case actionTypes.PHOTOS_UPDATE:
  return {
    ...state,
    photos: state.photos.concat(action.data.photos),
    photosTeamId: action.data.photosTeamId,
    photosProjectId: action.data.photosProjectId
  };

这里是点差运算符 [...]。扩展运算符可用于获取现有数组并向其添加另一个元素,同时仍保留原始数组。

例:

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

相关内容

  • 没有找到相关文章

最新更新