使用 react-router / react-router-redux 将特定的 redux 操作绑定到一个 Route

Bind specific redux action to one Route using react-router / react-router-redux

我目前正在使用 redux、react-router(具有 pushState History)和 react-router-redux 开发一个反应应用程序。我目前正在做的是将我的路由绑定到特定组件,就像我在每个文档中看到的最佳实践一样:

export default function (store) {
  return <Route path='/' component={CoreLayout}>
    <Route path="feed" components={{content: Feed}} />
    <Route path="f/:id" components={{content: FeedItem}} />
  </Route>
}

然后我的 Feed 组件中有一个 Link 组件,如下所示,它负责显示一个特定的条目:

<Link to={{ pathname: '/f/' + item.id + '-' + urlSlug(item.title) }}>{item.title}</Link>

然后 link 可以是类似 /f/123 的东西。因此,当我单击导航到项目 123 的 link 时,组件 FeedItem 被加载。到目前为止一切正常。我的 feeditem 也有一个特定的缩减程序,connected mapstatetoprops。我认为这一切都做对了。

但我现在的问题是:

我有一个名为 "SHOW_FEED_ITEM" 的动作。如果用户直接导航到 url /f/123,则应使用此操作,但理想情况下,如果用户单击 Link 组件。

但路由器实际执行的是触发 @@router/LOCATION_CHANGE 操作。在我的减速器中,我能够处理这个动作并派发我自己的动作,但我不喜欢这个解决方案,因为我必须从那里第二次解析路由 url 以重定向到正确的动作所有这些路线。

我现在正在做的是在我的 mapStateToProps 函数中接收 props.id(来自 Route f/:id)并将其传递给我的组件。这是我的组件提供正确 ID 的方式。

现在进入我的实际问题..

如果还告诉 Router 它应该处理哪个 Action 而不是仅仅告诉他它应该加载哪个组件不是更好吗?

我知道我可以向 Link 添加一个 onClick 处理程序来调度我的操作,但这只会影响对 link 的点击,不会影响浏览器 back/forth 甚至刷新用户动作。

现在这甚至可能已经成为可能吗? 你们是怎么处理的?

对于遇到相同问题和疑问的人:我发现 react-router 已经提供了解决方案。

每条路线都有可用的 onEnter 和 onLeave 属性。这基本上是在呈现路由之前挂钩的路由的回调函数。

onEnter

<Route path="route/:id" components={{content: MyComponent}} onEnter={()=>store.dispatch(myComponentsEnterAction())} />

休假

<Route path="route/:id" components={MyComponent} onLeave={()=>store.dispatch(myComponentsLeaveAction())} />

所以这是上面示例的完整路由器代码:

import React from 'react'
import { Route } from 'react-router'
import CoreLayout from './layout/corelayout'
import Feed from './components/feed/feed'
import FeedItem from './components/feed-item/feed-item'

export default function (store) {
  return <Route path='/' component={CoreLayout}>
    <Route path="feed" components={{content: Feed}} onEnter={()=>store.dispatch(displayFeed())} />
    <Route path="f/:id" components={{content: FeedItem}} onEnter={()=>store.dispatch(displayFeedItem())} />
  </Route>
}

可在此处找到更多相关信息: