这是我在React中与redux-thunk
和类组件一起使用的基本模式。下面的代码导出了一个类定义MyClass
,它与mapStateToProps
引入的状态正确连接,并且可以访问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___)
然而,当我试图定义一个抽象基类,这个抽象基类集中了某些到处都在使用的功能,并且它也需要连接到Redux时,上面的模式失败了。如果类MyClass___
是抽象的,我会在最后一行得到下面的错误:
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.
1条答案
按热度按时间jrcvhitl1#
这里有几点观察:
connect
API。hooks API通常使用起来要简单得多,* 而且 * 与TypeScript一起使用 * 要 * 容易得多 *。请在此处查看我们推荐的Redux和TypeScript使用模式: