0

I retrieve an array from database and set it to my slice.

[ { id: 'a01', name: 'name01' }, { id: 'a02', name: 'name02' }, { id: 'a03', name: 'name03' } ];

Users change the order with a user interface. When they change the order of the objects reorder reducer runs. It is a simple function which changes the positions of two objects inside array. Then boardAdapter.setAll sets the whole data.

Actually it works properly, but i realized an odd behaviour when all chars of id field are numbers as below. (e.g. id: '1' or id: '1234')

[ { id: '1', name: 'name01' }, { id: 'a02', name: 'name02' }, { id: 'a03', name: 'name03' } ];

This time reordering process works again properly but when it comes to returning that 'ordered' data and boardAdapter.setAll step, i see that ids being updated but entities still remain same.

Before reordering / After reordering

enter image description here

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
    }
});

I appreciate if anyone knows the reason. Thank you for your support.

4

1 回答 1

1

像您这样的 JavaScript 对象中键的顺序entities不能依赖于您正在使用的引擎,并且以正确的顺序构造一个新对象可能特别棘手 - 因此entityAdapter永远不会改变它,只会留下任何随机顺序(通常是插入顺序)。

“排序”的唯一来源是ids数组——使用你的选择器entityAdapter会给你返回内容,映射到正确的顺序。

于 2021-09-08T13:06:54.937 回答