小编典典

如何同步Redux状态和URL哈希标签参数

reactjs

我们提供了讲座和章节的列表,用户可以在其中选择和取消选择它们。这两个列表存储在redux存储中。现在,我们希望在url的hash标签中保留选定的演讲段和章节段的表示形式,并且对该URL所做的任何更改也应更改存储(双向同步)。

使用react-router甚至react-router-
redux
的最佳解决方案是什么?

我们找不到真正的好例子,其中react路由器仅用于维护url的hash标签,并且仅更新一个组件。


阅读 317

收藏
2020-07-22

共1个答案

小编典典

我认为您不需要。
(很抱歉,您的回答不屑一顾,但这是我的经验中最好的解决方案。)

存储是数据真实性的来源。这可以。
如果您使用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)
2020-07-22