如何将Redux与React类组件一起使用

k3bvogb1  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(199)

根据本教程,我正在尝试使用Redux和React类(typescript)。但是我有太多编译错误,我甚至不知道从哪里开始。显然我做错了什么。你能提供以下代码的实现和使用示例吗:

type CounterProps = {
  exampleProp: string;
};

type CounterState = {
  exampleState: string;
};

class CounterComponent extends React.Component<CounterProps, CounterState> {
  constructor(props: Readonly<CounterProps> | CounterProps) {
    super(props);
    this.state = {
      exampleState: '',
    };
  }
}

const mapStateToProps = (state: RootState) => {
  return {
    count: state.count,
  };
};

const mapDispatchToProps = {
  incrementCounter,
};

const connector = connect(mapStateToProps, mapDispatchToProps)(CounterComponent);

type PropsFromRedux = ConnectedProps<typeof connector>;
hjqgdpho

hjqgdpho1#

为了使用ConnectedProps<T>类型,你需要把连接分成两个步骤,否则你会有一个循环的类型引用(其中连接的组件类型依赖于内部组件类型,而内部组件类型依赖于连接的组件类型)。
首先,创建connector HOC,您可以从中获取类型。

const connector = connect(mapStateToProps, mapDispatchToProps);

type PropsFromRedux = ConnectedProps<typeof connector>;

第二步,将connector应用于基本组件。

const ConnectedCounter = connector(CounterComponent);

这样connector知道mapStateToPropsmapDispatchToProps的类型,但是它不知道CounterComponent的任何信息,所以它不是循环的.
如果你只是在学习,那么你绝对应该用函数组件来代替!

相关问题