【发布时间】: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.id或query.filter,所以我的标题仍然需要.split('/')每个案例的路径名。
标签: url-routing react-redux react-router-redux