使用react-router路由位置同步redux存储(路由更改时更新标头)

时间:2016-10-11 08:00:19

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

我正在使用react-router-redux并且我正在尝试更新我的应用的标头,只要路线发生变化(@@router/UPDATE_LOCATION

,就会从商店接收状态

目前我正在componentWillMount发送行动,如:

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

当我在路由componentWillMount上的/blocks/new中手动设置标头时,它是路由'blocks'的子节点,两者都有不同的标头,当我去的时候它不起作用回到history,因为路由blocks的组件不再安装,它仍然挂载。因此标题仍为New Block。当blocks挂载,而new仍未作为孩子卸载时,而不是之前它自己的标头。

(当我尝试用redux-devtools 逆转时间时,似乎发生了什么,每当我回到组件再次安装的点时,它将发送再次采取行动,开发者将接受另一次派遣。)

路线:

<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之外的任何其他内容来尝试找出我所在的路由,并且组件本身不应该为自己设置标题而烦恼(即在{{1 }})。

最后一个选项是使用路由器componentWillMount,但我想保持路由器清洁,但也许我需要妥协。

这里有什么我想念的吗?或者某种类型的lib可以帮助我解决这个问题?

TL; DR:如何让我的onEnter组件了解我们所处的路线,而不必分解header以确定我们的位置?

1 个答案:

答案 0 :(得分:0)

这是我的一个代码库中的代码。在这个应用程序中我使用哈希历史记录,但我认为你也可以用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'));