重新排序规范化Redux数据结构中的一系列对象(Reordering a sequence of objects in a normalised Redux data structure)

编程入门 行业动态 更新时间:2024-10-19 01:22:34
重新排序规范化Redux数据结构中的一系列对象(Reordering a sequence of objects in a normalised Redux data structure)

我有一个由字符串ID索引的规范化Redux数据结构。 在其他属性中,状态中的每个对象都有一个sequenceNumber ,用于在列表或网格中按顺序显示它。 可以拖放项目以重新排序它们。

我正在努力寻找一种简洁,纯粹的方法来更新序列号。 在Redux减速机中执行此操作的好方法是什么?


我当前的state数据结构基本上是:

{ 'asdf': { title: 'Item 1', sequence: 0, ... }, '1234': { title: 'Item 2', sequence: 1, ... }, 'zzzz': { title: 'Item 3', sequence: 2, ... } }

我的行动是

{ type: REORDER_ITEMS, oldRow: 1, newRow: 0 }

哪个应该导致国家

{ 'asdf': { title: 'Item 1', sequence: 1, ... }, '1234': { title: 'Item 2', sequence: 0, ... }, 'zzzz': { title: 'Item 3', sequence: 2, ... } }

我当前的reducer使用Object.keys(state).reduce()循环遍历项目并逐个修改sequence ,具体取决于它们是否等于,大于或小于所需的行号。 有没有更简洁的方法来管理这个?

I have a normalised Redux data structure indexed by a string ID. Amongst other properties, each object in the state has a sequenceNumber which is used to display it in order in a list or grid. The items can be dragged and dropped to reorder them.

I'm struggling to find a neat, pure approach to updating the sequence numbers. What is a good way to do this in a Redux reducer?


My current state data structure is essentially:

{ 'asdf': { title: 'Item 1', sequence: 0, ... }, '1234': { title: 'Item 2', sequence: 1, ... }, 'zzzz': { title: 'Item 3', sequence: 2, ... } }

My action is

{ type: REORDER_ITEMS, oldRow: 1, newRow: 0 }

Which should result in the state

{ 'asdf': { title: 'Item 1', sequence: 1, ... }, '1234': { title: 'Item 2', sequence: 0, ... }, 'zzzz': { title: 'Item 3', sequence: 2, ... } }

My current reducer uses Object.keys(state).reduce() to loop through the items and modify the sequence one by one, depending on whether they are equal, greater or lesser than the desired row numbers. Is there a neater way to manage this?

最满意答案

您可以进一步规范化步骤:在单独的状态切片中提取序列,并将订单存储为ID数组。

{ items : { 'asdf': { title: 'Item 1', ... }, '1234': { title: 'Item 2', ... }, 'zzzz': { title: 'Item 3', ... } }, sequence: ['1234', 'asdf', 'zzzz'] }

这样,您可以使用单独的reducer来处理修改序列的操作,只使用数组操作。

You could normalize a step further : Extract the sequence in a separate state slice and store the order as an array of ids.

{ items : { 'asdf': { title: 'Item 1', ... }, '1234': { title: 'Item 2', ... }, 'zzzz': { title: 'Item 3', ... } }, sequence: ['1234', 'asdf', 'zzzz'] }

This way, you could have a separate reducer to handle actions modifying your sequence, only using array operations.

更多推荐

本文发布于:2023-08-04 07:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1412537.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据结构   对象   系列   Reordering   Redux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!