【问题标题】:react-router access history prop in mapDispatchToPropsmapDispatchToProps 中的 react-router 访问历史记录道具
【发布时间】:2019-05-09 16:50:57
【问题描述】:

如何从mapDispatchToProps 访问history 属性

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 context props,docs 说:

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

更新:

这是react-router 的docs 对此的评价

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

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

【问题讨论】:

    标签: javascript reactjs react-redux react-router


    【解决方案1】:

    实现此目的的替代方法如下,但首先使用 console.log 检查道具中是否存在历史记录。

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

    你可以做这样的事情......

    【讨论】:

    • 实际上这是我现在的解决方法,但我认为MyComponent 不应该关心任何副作用实现,认为将history 作为道具并将其传递回它的父级,所有这些work 是 perent connected 组件的域。
    【解决方案2】:

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

    1. 作为组件属性传递给Router 作为<Route component = { MyConnectedComponent }/>
    2. 如果不是直接路由而是嵌套很深并且需要react-router 道具,用withRouter() 包裹它

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 2023-03-30
      • 2018-01-26
      • 2019-02-06
      • 1970-01-01
      • 2018-11-07
      • 2017-08-17
      • 2017-08-03
      • 2017-08-08
      相关资源
      最近更新 更多