简体   繁体   English

如何使用 immer 对数组进行排序?

[英]How can I sort an array using immer?

I'm trying to add an object to an array in a reducer, and after that, I would like to sort it by date (I can try to insert in order, but I think is more or less the same effort).我正在尝试将 object 添加到减速器中的数组中,然后,我想按日期对其进行排序(我可以尝试按顺序插入,但我认为或多或少是相同的努力)。

I'm using immer to handle the reducer immutability:我正在使用 immer 来处理减速器的不变性:

const newState = produce(prevState, (draftState) => {
  console.log(draftState);
  draftState.status = COMPLETE;
  draftState.current.entries.push(json.data);
    if (json.included) draftState.current.included.push(json.included);
});
return { ...initialState, ...newState };

The console.log showed there is printing this: console.log 显示正在打印:

Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true

So.. I don't really know how can I sort the draftState.current.entries array using immer.所以.. 我真的不知道如何使用 immer 对draftState.current.entries数组进行排序。

Any suggestions are welcome,欢迎任何建议,

Thanks谢谢

I ended up sorting the array first and then assigning that ordered array to draftState.current.entries我最终先对数组进行排序,然后将该有序数组分配给draftState.current.entries

let sortedEntries = prevState.current.entries.slice();
sortedEntries.push(json.data);
sortedEntries.sort((a, b) => new Date(b?.attributes?.date) - new Date(a?.attributes?.date));
const newState = produce(prevState, (draftState) => {
  draftState.status = COMPLETE;
  draftState.current.entries = sortedEntries;
  if (json.included) draftState.current.included.push(json.included);
});

return { ...initialState, ...newState };

To sort an array, without mutating the original array:要对数组进行排序,而不改变原始数组:

  • Call the slice() method on the array to get a copy.在数组上调用 slice() 方法以获取副本。
  • Call the sort() method on the copied array.在复制的数组上调用 sort() 方法。
  • The sort method will sort the copied array, without mutating the original. sort 方法将对复制的数组进行排序,而不会改变原始数组。

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

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