使用redux-thunk连接具有Redux状态的抽象类时出现问题

pbwdgjma  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(122)

这是我在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.
jrcvhitl

jrcvhitl1#

这里有几点观察:

  • 今天,你应该把React组件写成 * 函数 * 组件,而不是类。类仍然可以工作,但它们实际上已经被弃用了。正在进行的React docs rewrite在https://beta.reactjs.org上只教授函数组件,新的特性(如钩子)只适用于函数组件,而它们是React团队 * 希望 * 人们编写组件的方式。
  • 与此相关的是,即使你 * 正在 * 使用类组件the React team has advised against using class inheritance with React at all,你也应该使用组件组合来重用功能。
  • 类似地,Redux团队(我和伦茨Weber)特别推荐使用the React-Redux hooks API而不是传统的connect API。hooks API通常使用起来要简单得多,* 而且 * 与TypeScript一起使用 * 要 * 容易得多 *。

请在此处查看我们推荐的Redux和TypeScript使用模式:

相关问题