【问题标题】:Redux remove item from state based on object valueRedux 根据对象值从状态中删除项目
【发布时间】:2017-10-02 08:16:06
【问题描述】:

我的 redux 商店中有以下状态,它是包含对象数组的照片

每个对象都不同,我需要能够找到具有文件名的对象并删除我尝试使用索引和以下但没有真正工作的整个数组项

case actionTypes.PHOTO_DELETE:
           // return state.filter((photo) => photo.filename !== action.data)

            return { photos: state.photos.filter(photo =>
                photo.filename !== action.data
            )}

           // let index = state.photos.findIndex((photo) => photo.fillname === action.data);
            //console.log(index)
            /*
            var index = _.findIndex(action.data, function(photos) {
                return photos.photos == action.data
            })
            */
            //return update(state, {photoGroups: {$splice: [[index]]}});

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    通过检查内部数组中是否不存在具有指定文件名的对象来过滤照片数组。如果没有,那么findIndex() === -1

    return {
      photos: state.photos.filter(photo =>
        photo.findIndex(object => object.filename === action.data) === -1
      )
    }
    

    【讨论】:

      【解决方案2】:

      你可以destruct这个数组,这样你就不会改变它:

      const index = state.photos.findIndex(photos => 
        !photos.filter(photo => photo.filename === action.data)
      )
      
      return {
         ...state,
         photos: [
           ...state.photos.slice(0, index),
           ...state.photos.slice(index + 1),
        ],
      }
      

      【讨论】:

        【解决方案3】:

        您的方法的问题是您正在对照片数组进行比较,而在您的 json 数据中的照片数组中还有另一个数组。所以为了解决这个问题,在过滤器中使用过滤器来到达照片对象并比较文件名。

         return { 
           photos: state.photos.filter(photos => {
             const match = photos.filter(photo => (photo.filename === action.data));
             // return false if match is found
             // thus removing photos array from the data
             return !(match && match.length);
           })
         };
        

        【讨论】:

        • 这不起作用它会删除整个照片数组
        猜你喜欢
        • 2016-10-13
        • 1970-01-01
        • 2020-12-15
        • 2021-03-10
        • 1970-01-01
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 2020-10-24
        相关资源
        最近更新 更多