简体   繁体   中英

Problem using redux-thunk to connect an abstract class with Redux state

This is the basic pattern that I use with redux-thunk and class components in React. The below code exports a class definition MyClass which is properly connected with the state brought in by mapStateToProps and has access to the actions defined in mapDispatchToProps .

import React from 'react';
import { ThunkDispatch } from 'redux-thunk';

type OwnProps = ... // whatever
const mapStateToProps = (state: RootState, ownProps: OwnProps) => { return ... }
const mapDispatchToProps = (dispatch: ThunkDispatch)=>{ return ... }

const connector = connect(mapStateToProps, mapDispatchToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;

type Props = PropsFromRedux & OwnProps; 
type LocalState = ... // whatever


class MyClass___ extends React.PureComponent<Props, LocalState>

export const MyClass = connector(MyClass___)

However, the above pattern fails when I am trying to define a base abstract class that concentrates certain functionalities that are used all over the place and that it, too, needs to be connected to Redux. If the class MyClass___ is abstract I get the following error on the final line:

Argument of type 'typeof MyClass___' is not assignable to parameter of type 'ComponentType<never>'.
Type 'typeof MyClass___' is not assignable to type 'ComponentClass<never, any>'.
Cannot assign an abstract constructor type to a non-abstract constructor type.

Several observations here:

  • Today you should be writing React components as function components, not classes. Classes still work, but they're effectively deprecated. The in-progress React docs rewrite at https://beta.reactjs.org only teaches function components, new features like hooks only work with function components, and they're the way the React team wants people writing components.
  • Similarly, the Redux team (myself and Lenz Weber) specifically recommends using the React-Redux hooks API rather than the legacy connect API. The hooks API is much simpler to use in general, and it is vastly easier to use with TypeScript.

Please see our recommended patterns for using Redux and TypeScript here:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM