我认为您不需要。
(很抱歉,您的回答不屑一顾,但这是我的经验中最好的解决方案。)
存储是数据真实性的来源。这可以。
如果您使用React Router,请使其成为URL状态的真实来源。
您不必将所有物品都保留在商店中。
例如,考虑您的用例:
因为url参数仅包含讲座和所选章节的内容。在商店中,我有一个讲座和章节列表,其中包含名称,子句和选定的布尔值。
问题是您正在复制数据。存储(
chapter.selected)中的数据在React
Router状态下被复制。一种解决方案是同步它们,但这很快变得很复杂。为什么不让React Router成为某些章节的真实来源呢?
然后,您的商店状态如下所示(简化):
{ // Might be paginated, kept inside a "book", etc: visibleChapterSlugs: ['intro', 'wow', 'ending'], // A simple ID dictionary: chaptersBySlug: { 'intro': { slug: 'intro', title: 'Introduction' }, 'wow': { slug: 'wow', title: 'All the things' }, 'ending': { slug: 'ending', title: 'The End!' } }}而已!不要
selected在那里存放。相反,让React Router处理它。在路由处理程序中,编写类似
function ChapterList({ chapters }) { return ( <div> {chapters.map(chapter => <Chapter chapter={chapter} key={chapter.slug} />)} </div> )}const mapStateToProps = (state, ownProps) => { // Use props injected by React Router: const selectedSlugs = ownProps.params.selectedSlugs.split(';') // Use both state and this information to generate final props: const chapters = state.visibleChapterSlugs.map(slug => { return Object.assign({ isSelected: selectedSlugs.indexOf(slug) > -1, }, state.chaptersBySlug[slug]) }) return { chapters }}export default connect(mapStateToProps)(ChapterList)


