同步redux存储与react-router路由位置(更新报头在路由更改)



我使用的是react-router-redux,我正试图更新我的应用程序的头,从商店接收它的状态,每当路由改变(@@router/UPDATE_LOCATION)

当前我在componentWillMount中调度动作,如:

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

当我在路由/blocks/new上手动设置componentWillMount中的标头时,它是路由"块"的子,它们都有不同的标头,当我回到history时,它不起作用,因为路由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来弄清楚我们在哪里?

这是我的一个代码库中的代码。在这个应用程序中,我使用哈希历史,但我认为你也可以对其他历史对象做同样的事情。

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'));

最新更新