为了这个例子,我将讨论一个可重用的编辑器组件,它编辑文档并将它们提交到服务器。
在使用编辑器的代码中,我给每个编辑器一个唯一的 id。例如
const Comment = (props) => {
return <div>
<h3>Add new comment</h3>
<Editor editorId={`new-comment-${props.commentId}`} />
</div>
}
在 redux 状态下,我有一个 subreducer 编辑器,其对象由 editorId 键入,因此 redux 状态类似于:
{
otherStuff: {...},
editor: {
"new-comment-123": { isActive: true, text: "Hello there" },
"new-comment-456": { isActive: false, text: "" },
...
},
...
}
然后在编辑器mapStateToProps 我使用选择器来获取正确实例的数据:
const mapStateToProps = (state, ownProps) => {
return {
isActive: selectors.isActive(state, ownProps.editorId),
text: selectors.text(state, ownProps.editorId)
}
}
选择器以reselect 样式构建,可以手动构建,也可以实际使用重新选择。示例:
// Manual code
export const getEditor = (state, editorId) => state.editor[editorId] || {};
export const isActive = (state, editorId) => getEditor(state, editorId).
export const text = (state, editorId) => getEditor(state, editorId).text;
// Same in reselect
import { createSelector } from 'reselect'
export const getEditor = (state, editorId) => state.editor[editorId] || {};
export const isActive = createSelector([getEditor], (editorData) => editorData.isActive);
export const text = createSelector([getEditor], (editorData) => editorData.text);
如果你想扩展它以在多个应用程序中使用,你需要导出你的组件、reducer 和 sagas。有关工作示例,请查看 https://github.com/woltapp/redux-autoloader 甚至 http://redux-form.com