首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我们如何根据表列对createEntityAdapter进行排序?

我们如何根据表列对createEntityAdapter进行排序?
EN

Stack Overflow用户
提问于 2021-09-16 06:18:01
回答 1查看 2K关注 0票数 3

在我的React中,我使用Redux-带有entityAdapter的工具箱进行状态管理。如果我的表行是Redux-toolkit entityAdapter的实体,我想为每一列应用表排序。我想在我的减速器里像这样改变sortComparer函数。

代码语言:javascript
复制
sortEntities: (state,action) =>{
return {
...state,
sortComparer:(a:myEntityType,b:myEntityType)=> a.title.localCompare(b.title)
};
},

我在列的onClick处理程序上分派onClick操作。这种更改sortComparer不是抛出任何规则无效,而是不起作用。有人能帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-18 23:55:11

在上面的代码中,您要做的是将一个function存储到状态的sortComparer属性。实际上,您并没有将排序函数应用到任何地方,而且在Redux中存储不可序列化的数据(如函数)也是不可取的。

通过调用createEntityAdapter创建的适配器是一个帮助您与状态交互的对象。状态本身只是ids的数组和entities的字典对象。适配器的sortComparer属性不是状态的一部分,因此不能通过修改状态来修改它。

有很多方法来解决这个问题。

例如,您可以选择Redux的所有实体并在本地对它们进行排序。

代码语言:javascript
复制
const useSortedEntities = (sortBy) => {
   // get an array of entities with the selector from the entity adapter
   const allEntities = useSelector(selectEntities);

   // sort based on the current property
   // use ... to avoid mutation
   // would probably want to memoize this
   return [...allEntities].sort(
     (a, b) => a[sortBy].localCompare(b[sortBy])
   );
}
代码语言:javascript
复制
const SomeComponent = () => {
   const [sortProperty, setSortProperty] = useState('author');

   const sortedList = useSortedEntities(sortProperty);
...

或者您可以在有效负载中使用dispatch属性进行排序,并将排序属性保存在Redux中。然后可以使用createSelector为已排序的数据创建选择器。

代码语言:javascript
复制
const mySlice = createSlice({
    name: 'someName',
    initialState: myAdapter.getInitialState({
       // additional properties to include in initial state
       sortBy: 'author'
    }),
    reducers: {
       sortEntities: (state, action: PayloadAction<string>) => {
           state.sortBy = action.payload;
       }
...
代码语言:javascript
复制
const selectSortedEntities = createSelector(
   // first select entities with the selector from the adapter
   selectEntities,
   // next select the sort order
   (state: RootState) => state.pathToSlice.sortBy
   // then combine them to return a sorted array
   (allEntities, sortBy) => [...allEntities].sort(
        (a, b) => a[sortBy].localCompare(b[sortBy])
   );
)
代码语言:javascript
复制
const SomeComponent = () => {
   const sortedList = useSelector(selectSortedEntities);
   
   const dispatch = useDispatch();
   
   const onClick = () => {
       dispatch(sortEntities('title'));
   }
...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69203236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档