out*_*344 13 reactjs react-router
我在路由器上设置了browserHistory(react-router 2.0):
import { browserHistory } from 'react-router'
function requireAuth(nextState, replace) {
if (!services.auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
export default (store) => (
<Router history={browserHistory}>
<Route path='/' component={AppLayout}>
<Route path="login" component={LoginContainer} />
<Route path="map" component={MapContainer} onEnter={requireAuth} />
</Route>
</Router>
);
Run Code Online (Sandbox Code Playgroud)
然后我尝试在react-router中使用browserHistory以编程方式从视图路由到新页面,ala:
import { browserHistory } from 'react-router'
...
browserHistory.push('/map');
Run Code Online (Sandbox Code Playgroud)
这会将URL更改为/ map,但不会呈现该路由中的组件.我究竟做错了什么?
Mag*_*Guy 11
正如我在评论中所提到的那样,我遇到了同样的问题,但我找到了一种方法让它发挥作用.
这里发生的是你的路线正在改变,但你的AppLayout组件实际上并没有自动更新它的状态.路由器似乎不会自动强制对组件进行状态更改.基本上,this.state.children在你的AppLayout上没有更新新的孩子.
我找到的解决方案(并且,完全披露,我不知道这是你应该如何实现这一点,或者是否是最佳实践)是使用该componentWillReceiveProps函数并this.state.children使用新道具中的子项进行更新:
componentWillReceiveProps(nextProps) {
this.setState({
children: nextProps.children
});
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
7796 次 |
| 最近记录: |