browserHistory.push 不会导航到新页面 [英] browserHistory.push doesn't navigate to new page

查看:35
本文介绍了browserHistory.push 不会导航到新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在路由器上设置了 browserHistory(react-router 2.0):

I've set up browserHistory on a router with this (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:

I'm then trying to use browserHistory in react-router to programmatically route to a new page from a view, ala:

 import { browserHistory } from 'react-router'

 ...

 browserHistory.push('/map');

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

This changes the URL to /map but does not render the components in that route. What am I doing wrong?

推荐答案

正如我在评论中提到的,我遇到了同样的问题,但我已经找到了解决方案.

As mentioned in my comment I was having this same problem, but I've found a way to make it work.

这里发生的事情是您的 Route 正在更改,但您的 AppLayout 组件实际上并未自动更新其状态.路由器似乎不会自动强制对组件进行状态更改.基本上,您的 AppLayout 上的 this.state.children 不会随着新的孩子更新.

What's happening here is your Route is changing, but your AppLayout component isn't actually updating it's state automatically. The Router doesn't seem to automatically force a state change on the component. Basically, this.state.children on your AppLayout is not being updated with the new children.

我发现的解决方案(并且,完全公开,我不知道这是您应该如何实现这一目标,还是最佳实践)是使用 componentWillReceiveProps 函数并使用新道具中的孩子更新 this.state.children:

The solution that I found (and, full disclosure, I don't know if this is how you're supposed to achieve this, or if it's best practice) is to use the componentWillReceiveProps function and update this.state.children with the children from the new props:

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

希望这会有所帮助!

这篇关于browserHistory.push 不会导航到新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆