[英]How can I sort an array using immer?
我正在嘗試將 object 添加到減速器中的數組中,然后,我想按日期對其進行排序(我可以嘗試按順序插入,但我認為或多或少是相同的努力)。
我正在使用 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
所以.. 我真的不知道如何使用 immer 對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 };
要對數組進行排序,而不改變原始數組:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.