首页 文章

使用react-redux连接typescript

提问于
浏览
0

我'm trying to use React-redux connect with typescript. I'在使用 connectwithRouter 时感到困惑 .

我想尝试使用它,

withRouter<any>(connect<{},ComponentProps,{}>(
    matchStateToProps, 
    matchDispatchToProps
)(Component));

当试图传递属性 productList 它抛出,

TS2339:属性'productList'在类型'IntrinsicAttributes&IntrinsicClassAttributes,ComponentState >>&Rea ...上不存在

但在另一个组件中,

withRouter<any>(connect<{}, ComponentProps, {}>(
    mapStateToProps, 
    mapDispatchToProps
)(Component));

工作得很好 . ComponentProps 包含组件的所有属性 . (包括 statePropsdispatchPropsRouteProps ,和自己的道具) .

如何在types脚本中使用 connect 与react的 withRouter ?我应该传递什么作为 withRouterconnect 的道具?

2 回答

  • 0

    经过一些麻烦,我能够让这个工作!

    // assuming all these interfaces are well defined somewhere.
    type MyComponentProps = OwnProps & ComposeProps & StateProps & DispatchProps;
    
    // the secret sauce, need to define a class constructor to pass to compose
    interface MyComponentClass<MyComponentProps> extends React.ComponentClass {
      new (props: MyComponentProps): React.Component<MyComponentProps>;
    }
    
    export class MyComponent extends React.Component<MyComponentProps> {
      ...
    }
    
    export default compose<MyComponentClass<MyComponentProps>>(
      withSomeHOC(),
      connect<StateProps, DispatchProps, OwnProps>(mapStateToProps, mapDispatchToProps)
    )(MyComponent);
    

    以上将允许您导入组合组件并保持类型安全!

  • 0

    我是这样做的:

    import { compose } from 'redux';
    

    然后:

    export default compose<React.ComponentClass>(
      withRouter,
      connect<IMapStateToProps, IMapDispatchToProps, IConnectedRouterProps>(
        mapStateToProps,
        {
          fetchComponentData
        },
      ),
    )(Component);
    

相关问题