首页 文章

browserHistory.push无法导航到新页面

提问于
浏览
13

我在路由器上设置了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>
);

然后我尝试在react-router中使用browserHistory以编程方式从视图路由到新页面,ala:

import { browserHistory } from 'react-router'

 ...

 browserHistory.push('/map');

这会将URL更改为/ map,但不会呈现该路由中的组件 . 我究竟做错了什么?

2 回答

  • 11

    正如我在评论中所提到的那样,我遇到了同样的问题,但我找到了一种方法让它发挥作用 .

    什么's happening here is your Route is changing, but your AppLayout component isn'实际上更新它's state automatically. The Router doesn' t似乎会自动强制对组件进行状态更改 . 基本上,AppLayout上的 this.state.children 没有使用新的子项进行更新 .

    我发现的解决方案(并且,完全披露,我不应该实现这一点,或者如果这是最佳实践)是使用 componentWillReceiveProps 函数并使用新道具中的子项更新 this.state.children

    componentWillReceiveProps(nextProps) {
        this.setState({
            children: nextProps.children
        });
    }
    

    希望这可以帮助!

  • 2

    允许路由器导航到应用程序的另一部分而不必通过生命周期方法强制更新的替代解决方案是使用上下文路由器 . 您所需要的只是在组件中声明contextType(为了简洁省略路由器实例化和其他代码):

    class MyComp extends Component {
      static contextTypes = {
        router: PropTypes.object
      }
    
      handleClick = () => {
        this.context.router.push('/other/route')
      }
    }
    

    由于原因我不知道,browserHistory.push()对我来说不起作用,尽管browserHistory.goBack()和.goForward()都有 .

相关问题