【问题标题】:Sync redux store with react-router route location (update header on route change)将 redux 存储与 react-router 路由位置同步(在路由更改时更新标头)
【发布时间】:2016-10-11 08:00:19
【问题描述】:

我正在使用react-router-redux,并且我正在尝试更新我的应用程序的标头,该标头会在路线更改时从商店接收其状态 (@@router/UPDATE_LOCATION)

目前我正在componentWillMount 中发送操作,例如:

  componentWillMount() {
    this.props.appActions.setHeader('New Block')
  }

当我在路由 /blocks/new 上手动设置 componentWillMount 中的标题时,它是路由“块”的子节点,它们都有不同的标题,当我返回 @987654328 时它不起作用@,因为路由blocks的组件没有再次挂载,还是挂载的。因此标题仍然是New Block。而不是它自己的头文件之前的样子,当 blocks 挂载时,new 仍然作为孩子被卸载。

(当我尝试使用redux-devtools反转时间时,似乎会发生什么,每次我回到组件再次挂载的点时,它都会再次调度操作,并且 devtool 将收到另一个调度。)

路线:

<Route path="begin" component={PlayerBeginContainer}>
    <IndexRoute component={PlayerOverview}/>
       <Route path="blocks" component={PlayerBlocks}>
         <Route path="new" component={PlayerNewBlock}/>
       </Route>
</Route>
...

我尝试在路线更改时同步商店,但是:

if (action && action.type === UPDATE_LOCATION) {
 let path = action.payload.pathname.split('/')
 // Laboriously iterate through array to figure out what the new header state should be.
  // i.e. if (1 in split && split[1] === 'routeName')
  // or let lastPath = path[path.length - 1]
  // and getting parentPath would require more checking of whether it is the parent itself or not etc.
  // appHeader = 'routeHeader'
  return Object.assign({}, state, { appHeader: appHeader});
}

当您只需要它在特定子路由上触发时,这会变得非常乏味, 而且我想避免创建另一个嵌套结构,而我已经在路由器中定义了它。

在标题中,除了this.props.location.pathname 之外,我不能使用任何其他东西来尝试找出我在哪条路线上,并且组件本身不应该为自己设置标题而烦恼(即在componentWillMount 中)。

最后一个选择是使用路由器onEnter,但我想保持路由器清洁,但也许我需要在这方面做出妥协。

这里有什么我遗漏的吗?或者某种可以帮助我解决这个问题的库?

TL;DR:我怎样才能让我的header 组件知道我们在哪条路线上,而不必分解location.pathname 以确定我们在哪里?

【问题讨论】:

  • 您可以通过获取您提供给react-router-redux 的状态的位置片段来获取整个位置状态作为mapStateToProp 中相关反应组件的道具。一旦你把它作为道具,你应该能够做你想做的事。它可能最终会再次拆分路径名,但它似乎比听 UPDATE_LOCATION 操作更干净。
  • 这有帮助吗:github.com/reactjs/… ?
  • @iamnat,问题是,我没有使用params.idquery.filter,所以我的标题仍然需要.split('/') 每个案例的路径名。

标签: url-routing react-redux react-router-redux


【解决方案1】:

这是来自我的代码库之一的代码。在这个应用程序中,我使用哈希历史记录,但我认为您也可以使用 other history objects 做同样的事情。

import {hashHistory} from 'react-router';
import {syncHistoryWithStore} from 'react-router-redux';

const history = syncHistoryWithStore(hashHistory, store);
history.listen(location => {
   // here you can do something after location is updated
});

<Router history={history}>
 ....
</Router>

然后在您的组件中,您可以从 state.routing 获取一些信息:

function mapStateToProps(state) {
  return {
    current: state.routing.locationBeforeTransitions.pathname,
  };
}

export default connect(mapStateToProps)(App);

要从某个组件更改路由,请执行以下操作:

import {push} from 'react-router-redux';
this.props.dispatch(push('/route'));

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 2016-09-21
    • 2018-09-04
    • 2022-10-04
    • 2017-12-24
    • 2019-06-04
    • 1970-01-01
    • 2017-06-10
    • 2016-10-21
    相关资源
    最近更新 更多