我有一个由字符串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.
更多推荐
发布评论