【问题标题】:browserHistory.push doesn't navigate to new pagebrowserHistory.push 没有导航到新页面
【发布时间】:2016-06-02 07:06:55
【问题描述】:

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

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,但不会呈现该路由中的组件。我做错了什么?

【问题讨论】:

  • 我可以看看你的requireAuth 处理程序,还有地图视图吗?
  • 好的 - 已添加。注意:如果我没有 onEnter 属性,也会发生同样的事情(/map 未呈现)。
  • 是的 - 调用了 browserHistory.push('/map') - 我看到 URL 发生了变化,但是新的 Route 组件 (MapContainer) 没有呈现。最后,为了完整起见,如果我关闭 auth,然后直接转到 /map,它会正确呈现。
  • 您是否在此应用程序后面使用服务器? Nginx,还是别的什么?这些需要设置为使用全部路由并将所有内容发送到 index.html。我相信你可能知道。因为你有使用 ember 的经验。
  • 是的 - 我特别使用这个应用程序种子:github.com/davezuko/react-redux-starter-kit

标签: reactjs react-router


【解决方案1】:

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

class MyComp extends Component {
  static contextTypes = {
    router: PropTypes.object
  }

  handleClick = () => {
    this.context.router.push('/other/route')
  }
}

由于我不知道的原因,browserHistory.push() 对我不起作用,尽管 browserHistory.goBack() 和 .goForward() 起作用。

【讨论】:

    【解决方案2】:

    正如我在评论中提到的,我遇到了同样的问题,但我找到了一种让它工作的方法。

    这里发生的是您的 Route 正在更改,但您的 AppLayout 组件实际上并没有自动更新它的状态。路由器似乎不会自动强制组件更改状态。基本上,您的 AppLayout 上的 this.state.children 不会使用新的子项进行更新。

    我找到的解决方案(并且,完全披露,我不知道这是否是您应该实现此目标的方式,或者它是否是最佳实践)是使用 componentWillReceiveProps 函数并更新 this.state.children与来自新道具的孩子们:

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

    希望这会有所帮助!

    【讨论】:

    • 这似乎是最好的方法,但这是我在互联网上可以找到的唯一答案,加上 github 上的文档非常平庸。您能否以任何可能的方式对此进行扩展。我不确定在我的顶级组件容器我的路由器中我应该在哪里使用componentWillReceiveProps?我正在使用 var children = React.Children.map(children, function (child) { return React.cloneElement(child, { user: user, key: key }); });在纯 js 函数中克隆我的道具。
    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多