You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Toolkit调用EntityAdapter的setAll方法仅第一条数据存入问题

问题原因
  • Redux Toolkit 中 createEntityAdapter 默认使用数据中的 id 字段作为唯一主键,你的播客数据主键为 _id (常见为MongoDB生成的主键格式),和默认主键规则不匹配。当多个条目的默认取id结果一致时,setAll 操作会判定为同一条数据,仅保留一条。
  • 你在初始化状态时手动覆盖了 entities 字段为数组,而 createEntityAdapter 内置的 entities 是键为id、值为对应数据的对象格式,类型不匹配也会导致适配器操作异常。
修复方案
  1. 初始化适配器时指定主键选择器,适配你的_id字段:
// 修改前
// const podcastAdapter = createEntityAdapter();
// 修改后
const podcastAdapter = createEntityAdapter({
  selectId: (podcast) => podcast._id
});
  1. 移除初始状态中手动定义的entities字段,直接使用适配器内置的结构即可:
initialState: podcastAdapter.getInitialState({
  loading: 'idle'
} as podcastState),
  1. 若开启TypeScript校验,同步修改podcastState类型定义,适配适配器的内置字段格式:
interface podcastState {
    entities: Record<string, Podcast>
    ids: string[]
    loading: 'idle' | 'loading' | 'successed' | 'failed'
}
可选优化

你无需自定义selectPodcastIds选择器,适配器自带的selectIds方法已经返回所有主键的数组,直接导出使用即可:

export const {
    selectById: selectPodcastById,
    selectAll: selectPodcasts,
    selectIds: selectPodcastIds
} = podcastAdapter.getSelectors((state: any) => state.podcasts)

内容的提问来源于stack exchange,提问作者Hasan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:06:04