3

我正在尝试将一个对象添加到减速器中的数组中,然后,我想按日期对其进行排序(我可以尝试按顺序插入,但我认为或多或少是相同的努力)。

我正在使用 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 };

console.log 显示正在打印:

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

所以.. 我真的不知道如何draftState.current.entries使用 immer 对数组进行排序。

欢迎任何建议,

谢谢

4

1 回答 1

3

我最终先对数组进行排序,然后将该有序数组分配给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 };
于 2020-08-20T13:19:14.387 回答