78

我们有一个讲座和章节列表,用户可以在其中选择和取消选择它们。这两个列表存储在一个 redux 存储中。现在我们想要在 url 的 hash 标记中保留选定的讲座 slug 和章节 slug 的表示,并且对 url 的任何更改也应该更改存储(双向同步)。

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

我们真的找不到一些好的例子,其中 react 路由器仅用于维护 url 的哈希标记,并且也只更新一个组件。

4

2 回答 2

152

我认为你不需要。
(对不起,一个不屑一顾的答案,但这是我经验中最好的解决方案。)

存储是数据的真实来源。这可以。
如果你使用 React Router,让它成为你 URL 状态的真实来源。
您不必将所有东西都保存在商店中。

例如,考虑您的用例:

因为 url 参数只包含讲座的 slug 和选择的章节。在商店中,我有一个讲座和章节列表,其中包含名称、slug 和选定的布尔值。

问题是您正在复制数据。store ( 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)
于 2016-04-20T16:34:12.020 回答
3

react-router-redux可以帮助您注入要存储的 url 内容,因此每次哈希标签更改时,也要存储。

于 2016-04-20T10:29:33.070 回答