Javascript mapDispatchToProps中的react路由器访问历史记录道具

Javascript mapDispatchToProps中的react路由器访问历史记录道具,javascript,reactjs,react-redux,react-router,Javascript,Reactjs,React Redux,React Router,如何从mapDispatchToProps import { withRouter } from "react-router-native"; const mapDispatchToProps = (dispatch, ownProps) => ({ doSomething: () => ownProps.history.goBack() // history is undefined ...?? }) export default withRouter(connect(

如何从
mapDispatchToProps

import { withRouter } from "react-router-native";

const mapDispatchToProps = (dispatch, ownProps) => ({
   doSomething: () => ownProps.history.goBack() // history is undefined ...?? 
})

export default withRouter(connect(undefined, mapDispatchToProps)(MyComponent))
更清楚地了解如何从
connect
mapDispatchToProps
方法中访问
react router
上下文道具:

如果mapDispatchToProps函数声明为采用两个参数,则将调用该函数,并将dispatch作为第一个参数,将props作为第二个参数传递给连接的组件

更新:

下面是
react router
对这一点的看法

在大多数情况下,您可以使用链接、导航链接和重定向来执行导航操作。有时,在最初由操作启动的某个异步任务之后,您可能还需要以编程方式导航。例如,当用户提交登录表单时,您可能会发送一个操作。然后,thunk、saga或其他异步处理程序对凭据进行身份验证,如果成功,则需要以某种方式导航到新页面。这里的解决方案只是将历史对象(提供给所有路由组件)包含在操作的有效负载中,并且您的异步处理程序可以在适当的时候使用它来导航


显然,在连接的组件中不支持外部上下文,需要找到适当的干净解决方法。

实现这一点的替代方法如下,但首先使用console.log检查props中是否有历史记录

const mapDispatchToProps = (dispatch, ownProps) => ({
 doSomething: (history) => history.goBack() // history is undefined ...?? 
})

您可以这样做…

实现这一点的替代方法如下,但首先使用console.log检查道具中是否有历史记录

const mapDispatchToProps = (dispatch, ownProps) => ({
 doSomething: (history) => history.goBack() // history is undefined ...?? 
})

您可以这样做……

对于任何遇到此问题的人,您可以从
mapDispatchToProps
中的
ownProps
访问
react router
上下文道具,但请确保您的连接组件位于以下位置之一:

  • 作为组件道具传递给
    路由器
    作为
  • 如果它不是直接路由,而是嵌套的深路由,并且需要
    react router
    props,请使用
    withRouter()

  • 对于遇到此问题的任何人,都可以从
    mapDispatchToProps
    中的
    ownProps
    访问
    react router
    上下文道具,但请确保您的连接的组件位于以下位置之一:

  • 作为组件道具传递给
    路由器
    作为
  • 如果它不是直接路由,而是嵌套的深路由,并且需要
    react router
    props,请使用
    withRouter()

  • 实际上这是我现在的解决方法,但我不认为MyComponent
    应该关心任何副作用的实现,我认为把
    历史
    作为道具,并将其传递回它的父级,所有的工作都是perent
    连接的
    组件的领域。实际上,这是我现在的解决方法,但是我认为
    MyComponent
    不应该关心任何副作用的实现,我认为将
    history
    作为道具并将其传递回它的父组件,所有这些工作都是perent
    连接的
    组件的领域。