我从数据库中检索一个数组,并将其设置为我的切片。
[ { id: 'a01', name: 'name01' }, { id: 'a02', name: 'name02' }, { id: 'a03', name: 'name03' } ];用户通过用户界面更改顺序。当它们更改对象的顺序时,reorder reducer将运行。这是一个简单的函数,可以改变数组中两个对象的位置。然后boardAdapter.setAll设置整个数据。
实际上它工作正常,但当id字段的所有字符都是数字时,我发现了一个奇怪的行为,如下所示。(例如id:'1‘或id:'1234')
[ { id: '1', name: 'name01' }, { id: 'a02', name: 'name02' }, { id: 'a03', name: 'name03' } ];这一次的重新排序过程再次正常工作,但当涉及到返回“有序”数据和boardAdapter.setAll步骤时,我看到ids正在更新,但entities仍然保持不变。
重新排序前/重新排序后

import { createSlice, createAsyncThunk, createEntityAdapter } from '@reduxjs/toolkit';
const boardAdapter = createEntityAdapter({});
export const reorder = createAsyncThunk('board/reorder', async ({ result, sections }) => {
const { source, destination } = result;
const ordered = reorderSection(sections, source.index, destination.index);
return ordered;
});
const reorderSection = (sections, startIndex, endIndex) => {
const result = Array.from(sections);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const boardSlice = createSlice({
name: 'board',
reducers: {
resetBoard: (state, action) => null,
}
extraReducers: {
[reorder.fulfilled]: boardAdapter.setAll
}
});如果有人知道原因,我将不胜感激。谢谢您一直鼓励我。
发布于 2021-09-08 13:06:55
像entities这样的JavaScript对象中键的顺序不能依赖于您正在使用的引擎,用正确的顺序构造新对象可能特别困难-因此entityAdapter永远不会改变它,只会保留任何随机的顺序(通常是插入的顺序)。
“排序”的唯一来源是ids数组-使用entityAdapter的选择器将返回内容,并映射为正确的顺序。
https://stackoverflow.com/questions/69101892
复制相似问题