【问题标题】:Redux 'connect' function with Typescript带有 Typescript 的 Redux 'connect' 功能
【发布时间】:2019-09-30 21:21:24
【问题描述】:

我正在使用 Redux 和 Typescript 编写一个 React Native 应用程序。我一直在看其他人的代码(我不能逐字分享),当他们使用connect 函数时,它看起来像这样:

export default connect<a, b, c, d>(
  state => ({
  ...
  }),
  dispatch => bindActionCreators({
  ...
  }, dispatch)
)(<Component name>)

谁能解释a, b, c, d 参数的用途是什么?我知道这涉及 Typescript 泛型,但谁能让我更深入地了解 connect 如何使用这些?

谢谢!

【问题讨论】:

    标签: reactjs typescript react-native redux react-redux


    【解决方案1】:

    这里是带有ite接口的connect方法的详细信息:

    <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = {}>(
            mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
            mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>
        ): InferableComponentEnhancerWithProps<TStateProps & TDispatchProps, TOwnProps>;
    

    更多详情请访问typescript-and-react-redux-connect

    【讨论】:

      【解决方案2】:

      从语法上看,它非常冗长。

      connect 上的泛型旨在推断而不是静态传递(尽管有一些例外。

      bindActionCreators 也不再需要,因为第二个参数对象值将自动与调度绑定

      IE上面的代码可以简化为...

      const mapStateToProps(state: IGlobalState) => {
           return {
              // add things you want from your state here.
           }
      
      } // if you don't want anything from your state you can pass null.
      
      export const withState = connect(mapStateToProps, {addTodo: TodoActions.add})(ComponentName)
      
      export const withNoState = connect(null, {addTodo: TodoActions.add})(ComponentName)
      export const withNeither = connect()(ComponentName) // at first glance looks useless but this will actually give you access to 'dispatch' inside your component.
      
      

      【讨论】:

        猜你喜欢
        • 2019-11-14
        • 2017-09-12
        • 2020-08-14
        • 1970-01-01
        • 2018-07-22
        • 2020-12-30
        • 2021-11-24
        • 2020-10-09
        • 1970-01-01
        相关资源
        最近更新 更多