在不重置状态的情况下删除与数组映射的 SwiperJS 中的幻灯片 [英] Deleting a slide in SwiperJS mapped with an array without the state resetting

查看:30
本文介绍了在不重置状态的情况下删除与数组映射的 SwiperJS 中的幻灯片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经与这个问题搏斗了很长一段时间,但一直无法弄清楚这一点.

衷心感谢您的帮助,谢谢!

解决方案

更新代码沙盒.为了防止重新渲染所有其他数组元素,每个元素的键在渲染中必须是唯一的.通过将键设置为计数来修复,该计数严格递增.

我错过了一个非常重要的事实,即对于非静态数组,您不能使用数组的索引作为键,因为这会在重新洗牌/删除元素时触发重新渲染,因此键应该是对于每个元素都是唯一的,并且在数组更改中持续存在.在大多数用例中,基于递增计数器的简单 ID 非常适用于此.

I've been wrestling with this issue for quite a while now, but have not been able to figure this out. Code Sandbox demo here.

I have a set of slides rendered with SwiperJS. I need to render this through mapping an array out. I have been able to push to the back of this array successfully, but deletion is an issue. There are two ways of doing this. First, I can delete the element at a specific index by changing the state of my array. This "works" but the problem is that the state of each rendered component is not saved.

I know that there is a removeSlide() function but the issue is that the array mapping then gets messed up because if I delete from my array as well, it's a double delete.

Now I think that directly modifying the array in my state is the way to go, but there's a problem with the components being rendered all having their states reset. In the linked sandbox, you can reproduce this by adding any number of slides, randomizing the states on each slide, and then deleting the current slide. All their states will be reset due to the re-render.

Here's a video of it happening. In this video, I add a slide, randomize the state in both of the slides, then delete the first slide. The state of the 2nd slide (which is now the 1st slide) will be reset. This happens to any arbitrary number of slides:

Sincerely appreciate any help, thanks!

解决方案

Updated Code Sandbox. To prevent re-rendering of all other array elements, the key of each element must be unique across renders. Fixed by setting the key to be a count, which is strictly increasing.

I missed this very important fact that for non-static arrays, you cannot use the index of the array as the key, because this will trigger re-renders when elements are reshuffled/deleted, and hence the key should be something that is unique for every element, and persists across array changes. A simple ID based on an incrementing counter works well for this in most use cases.

这篇关于在不重置状态的情况下删除与数组映射的 SwiperJS 中的幻灯片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆