React Native + Redux:在Redux存储和渲染中对对象重新排序

时间:2020-01-08 22:46:55

标签: javascript react-native redux react-redux

我有一个组件,该组件使用 react-native-sortable-grid 中的 SortableGrid 来渲染照片网格,可以将其拖动以重新排列图像。网格的数据是从我的redux存储中的一个对象提供的。我目前可以上传和删除图像,但是我正在努力使图像正确重新排序。

我的减速器:

const INITIAL_STATE = {
  user: {
      // ... other fields ommitted
      photos: {"0" : null,
               "1" : null,
               "2" : null,
               "3" : null,
               "4" : null,
               "5" : null},
      }
  }


const userReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
      case 'SETPHOTOS':
         return {
             ...state,
             user: {
                 ...state.user,
                 photos : action.payload,
             }
         }
 }

与重新排序功能一起呈现的组件:

 const PhotoUpload = ({ navigation }) => {


    // Redux hooks
    const photos = useSelector(state => state.user.user.photos);
    const dispatch = useDispatch();


    // function to reorder the images
    reorderImages = (itemOrder) => {
      const temp = {}
      const photosCopy = {...photos}

      const array = itemOrder.itemOrder

      for (let index = 0; index < array.length; index++) { 
         let e = array[index]
         let key = e.key
         let order = e.order

         temp[order] = photosCopy[key]
      }

      dispatch(setStorePhotos(temp));
    }


    return (
     <>
        <SortableGrid
        // ... other props ommitted
        onDragRelease       = { (itemOrder) => reorderImages(itemOrder) }
        onDragStart         = { (photo) => console.log("Block: ", photo, " is being dragged now!") } >

        {
            Object.keys(photos).map((key) => 

               <View key={ key } onTap={() => this.pickSingle(true, false, key)} >
                   <Image defaultSource={ require('./default-avatar.png') } source={ getPhoto(key) } />
                   //... add/delete buttons ommitted
               </View>

            )
        }
        </SortableGrid>
     </>
  )
}

释放拖动后,我调用reorderImages,并向其传递一个与网格中图像顺序相对应的对象。这是交换两个图像后传递给我的函数的itemOrder对象:

    {"itemOrder": 
    [{"key": "1", "order": 0, "ref": null},
     {"key": "0", "order": 1, "ref": null},
     {"key": "2", "order": 2, "ref": null}, 
     {"key": "3", "order": 3, "ref": null}, 
     {"key": "4", "order": 4, "ref": null}, 
     {"key": "5", "order": 5, "ref": null}]}

这是上传2张图片后网格的外观: After uploading 2 images 上传2张图片后登录:

Photos:
 LOG  0 IMG_0001.JPG
 LOG  1 IMG_0002.JPG
 LOG  2 null
 LOG  3 null
 LOG  4 null
 LOG  5 null

然后我将第一张图像拖到第二张上并释放,但是一旦释放,图像就会切换位置。交换2张图片后登录:

Photos:
 LOG  0 IMG_0002.JPG
 LOG  1 IMG_0001.JPG
 LOG  2 null
 LOG  3 null
 LOG  4 null
 LOG  5 null

日志中的图像顺序是正确的,但是网格与图片1处于相同状态。因此,当我删除第一个图像(第二个图像应向左滑动)时,它将保持原状。

After deleting the first image, the second image should slide over to the first index 我花了太多时间试图解决这个问题,因此我将不胜感激。

0 个答案:

没有答案