browserHistory.push() 和 context.router.push() 有什么区别

What's the different between browserHistory.push() and context.router.push()

我正在学习 React Route 以帮助我构建一个可以在成功登录后从登录页面重定向到主页的应用程序。

我在这里看了官方教程:https://github.com/reactjs/react-router-tutorial/tree/master/lessons/12-navigating

在本课中,他们介绍了两种以编程方式导航的方法,即 browserHistory 和 context.route。他们说 browserHistory 有一个潜在的问题:

If you pass a different history to Router than you use here, it won't work. It's not very common to use anything other than browserHistory, so this is acceptable practice.

你能举例说明什么是 If you pass a different history to Router than you use here 吗?

我在我的应用程序中尝试了这两种方式,但找不到任何区别。谢谢!

这是一个非常古老的教程。我建议改为查看 official react router documentation

您提供的示例直接使用 browserHistory 实例调用 history api 方法。如果您将 React 路由器配置为使用浏览器历史记录,这将起作用,但是有不同的历史记录类型(哈希历史记录、内存历史记录等),甚至可能有多个 browserHistory 实例。虽然所有不同的历史记录类型都支持 push 方法,但如果您最初将 React 路由器配置为使用哈希历史记录,但在您的组件中,您导入了浏览器历史记录,则推送调用将无法正常工作,因为您的路由器未配置为侦听该浏览器历史实例。

虽然您可以使用上下文来获取路由器实例,但更简洁的方法是使用 withRouter HOC 将路由器实例作为 prop 注入到您的组件中。然后您可以调用 router.push 而不必担心您使用的是哪种历史记录。

您可以阅读更多有关历史的信息here