我正在尝试将对象添加到 reducer 中的数组,之后,我想按日期对其进行排序(我可以尝试按顺序插入,但我认为或多或少是相同的努力) .
我正在使用 immer 来处理 reducer 的不可变性:
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 };
关于javascript - 如何使用 immer 对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62944622/