在我的React中,我使用Redux-带有entityAdapter的工具箱进行状态管理。如果我的表行是Redux-toolkit entityAdapter的实体,我想为每一列应用表排序。我想在我的减速器里像这样改变sortComparer函数。
sortEntities: (state,action) =>{
return {
...state,
sortComparer:(a:myEntityType,b:myEntityType)=> a.title.localCompare(b.title)
};
},我在列的onClick处理程序上分派onClick操作。这种更改sortComparer不是抛出任何规则无效,而是不起作用。有人能帮我吗?
发布于 2021-09-18 23:55:11
在上面的代码中,您要做的是将一个function存储到状态的sortComparer属性。实际上,您并没有将排序函数应用到任何地方,而且在Redux中存储不可序列化的数据(如函数)也是不可取的。
通过调用createEntityAdapter创建的适配器是一个帮助您与状态交互的对象。状态本身只是ids的数组和entities的字典对象。适配器的sortComparer属性不是状态的一部分,因此不能通过修改状态来修改它。
有很多方法来解决这个问题。
例如,您可以选择Redux的所有实体并在本地对它们进行排序。
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])
);
}const SomeComponent = () => {
const [sortProperty, setSortProperty] = useState('author');
const sortedList = useSortedEntities(sortProperty);
...或者您可以在有效负载中使用dispatch属性进行排序,并将排序属性保存在Redux中。然后可以使用createSelector为已排序的数据创建选择器。
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;
}
...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])
);
)const SomeComponent = () => {
const sortedList = useSelector(selectSortedEntities);
const dispatch = useDispatch();
const onClick = () => {
dispatch(sortEntities('title'));
}
...https://stackoverflow.com/questions/69203236
复制相似问题