Reputation: 1
I am trying to use Redux with React Class (typescript), according to this tutorial. But I have so many compilation errors that I don't even know where to start. Obviously I'm doing something wrong. Can you please provide an implementation and usage example for the following code:
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>;
Upvotes: 0
Views: 866
Reputation: 42160
In order to use the ConnectedProps<T>
type, you need break the connecting into two steps. Otherwise you would have a circular type reference (where the connected component types depend on the inner component types, which depend on the connected component types).
First, you create the connector
HOC, which you can get the types from.
const connector = connect(mapStateToProps, mapDispatchToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;
Second, you apply the connector
to the base component.
const ConnectedCounter = connector(CounterComponent);
This way the connector
knows about the types from mapStateToProps
and mapDispatchToProps
, but it does not know anything about CounterComponent
. So it's not cyclical.
If you are just learning then you should absolutely learn with function components instead!
Upvotes: 1