简体   繁体   English

在 Redux reducer 中对对象数组进行排序

[英]Sorting array of objects in Redux reducer

I am trying to sort an array like this (my state):我正在尝试对这样的数组进行排序(我的状态):

[
  {
    name:"Aenean in justo ante"
  },
  {
    name:"Phasellus viverra mattis dolor"
  }
]

I dispatch an action to the reducer: (part of reducer)我向减速器发送一个动作:(减速器的一部分)

case 'SORT_COLLECTION':
  return state.sort(function(a, b) {
    var nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase();
    if (nameA < nameB) {
      return -1;
    }
    if (nameA > nameB) {
      return 1;
    }
    return 0;
  })

but it does not work.但它不起作用。 Could somebody tell me where the mistake is?有人能告诉我错误在哪里吗?

The sorting function should work fine.排序功能应该可以正常工作。 But you should not mutate the original state in the reducer.但是你不应该改变reducer中的原始状态。 You can create a copy of the state array by calling state.slice() before sorting.您可以通过在排序前调用state.slice()来创建state数组的副本。

case 'SORT_COLLECTION':
  return state.slice().sort(function(a, b) {
    var nameA = a.name.toLowerCase(),
      nameB = b.name.toLowerCase()
    if (nameA < nameB)
      return -1
    if (nameA > nameB)
      return 1
    return 0
  })

Of course, you can define a simpler sort function as well.当然,您也可以定义更简单的排序函数。

 const state = [{name:'foo'},{name:'bar'},{name:'baz'}] const sortByKey = key => (a, b) => a[key] > b[key] ? 1 : -1 const sorted = state.slice().sort(sortByKey('name')) console.log(`state=${JSON.stringify(state)}\\nsorted=${JSON.stringify(sorted)}`)

You need to do:你需要做:

state.slice().sort(...

As sort() changes the original array by reordering references (mutates it) which is a "no go" for redux store.由于sort()通过重新排序引用(改变它)来更改原始数组,这对于 redux 存储来说是“不行的”。 slice() first does a shallow copy meaning only references are copied and it is fast (unless it contains primitives in which case they will be copied, but it will still be fast) and then those new references are moved around by sort() . slice()首先做一个浅拷贝,这意味着只复制引用并且它很快(除非它包含基元,在这种情况下它们将被复制,但它仍然会很快)然后这些新引用通过sort()

NOTE: you still can not change the objects within the array, but luckily sort does not change them.注意:您仍然无法更改数组中的对象,但幸运的是 sort 不会更改它们。

The Array.prototype.sort method requires you to return an integer or a boolean . Array.prototype.sort方法要求您返回一个integer或一个boolean

The below shows how to order in either direction.下面显示了如何在任一方向订购。

 var arr = [ { name:"Aenean jon justo ante" }, { name:"Aenean in justo ante" }, { name:"Phasellus viverra mattis dolor" } ] console.log("Alphabetical:", arr.sort((a,b) => a.name > b.name)); console.log("Reversed:", arr.sort((a,b) => a.name < b.name));

如果您使用的是 es6,您可以尝试这样state.sort((a,b) => a.name - b.name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM