首页 > 解决方案 > Redux:为主减速器的子元素构建减速器

问题描述

可能是个愚蠢的问题。我有一个从 Immutable.js 记录构建的 Redux reducer:

export const Editors = new Record({
    'editors': new List(), // this is a list of Editor items below
})

export const Editor = new Record({    
    'id': null,
    'state': EditorState.createEmpty(),
    'annotations': new List(),
});

我以这种方式组织事物,因为我希望我正在构建的应用程序有很多编辑器。

但是,我想编写一个updateState更新单个编辑器状态的操作。Editor我想如果我能够编写对特定而不是Editor在我的减速器中的 s列表起作用的减速器代码,那么编写它会容易得多Editors。有没有办法编写 reducer 代码,这样我就可以在单个编辑器中更新字段的状态,而不是在列表中找到编辑器、删除它、更新它、重新插入它等等?

标签: redux

解决方案


export const Editors = new Record({
    'editors': new Map(), // this is a list of Editor items below
})

export const Editor = new Record({    
    'id': null,
    'state': EditorState.createEmpty(),
    'annotations': new List(),
});

然后更新编辑器变为:

const updateEditorState = (Editors, id, editorState) =>
   Editors.setIn(['editors', id, 'state']¸editorState)

顺便说一句,你的命名有点奇怪。我会小写EditorsEditor.


推荐阅读