使用createSelector按updatedAt排序对话的问题求助
问题描述
我有一个对话列表,想按照updatedAt属性对其排序,请问使用Redux的createSelector时,能否用下面这种写法?
export const getSortedConversations = createSelector( (state) => state.entities.chat, (chat) => chat.conversations.sort((a, b) => a.updatedAt - b.updatedAt) )
我试了这个写法,但使用该selector时,对话完全没被设置到状态里。
解决方案
你的写法存在一个核心问题:Array.sort()是原地排序方法,它会直接修改原数组chat.conversations——也就是Redux状态里的原始数据。而Redux要求状态必须保持不可变性,直接修改原状态会导致Redux无法检测到状态变化,组件也就拿不到更新后的数据,看起来就像对话没被设置到状态里。
正确的做法是先复制原数组,再对副本进行排序,这样不会触碰Redux的原始状态:
export const getSortedConversations = createSelector( (state) => state.entities.chat, (chat) => [...chat.conversations].sort((a, b) => a.updatedAt - b.updatedAt) )
也可以用slice()创建数组副本:
export const getSortedConversations = createSelector( (state) => state.entities.chat, (chat) => chat.conversations.slice().sort((a, b) => a.updatedAt - b.updatedAt) )
这样每次排序都会返回一个新数组,createSelector能正确识别到数据变化,组件也能正常获取到排序后的对话列表。
内容的提问来源于stack exchange,提问作者Frisbetarian-Support Palestine
相关产品推荐
相关产品推荐

