Home > Software engineering >  Something wrong with react-redux and component with children
Something wrong with react-redux and component with children

Time:04-01

I think there is something I don't get with typings using react-redux. Consider this :

import React from 'react';
import { Text } from 'react-native';
import { connect } from 'react-redux';
import { AnyAction } from 'redux';
import { ThunkDispatch } from 'redux-thunk';

function SomeComponent_Unconnected(
  props: React.PropsWithChildren<{ foo: string; handleSmth: () => void }>
) {
  return <>
    <Text>{props.foo}</Text>
    {props.children}
    </>;
}

interface IState {
  foo: string;
}

const SomeComponent = connect(
  // map state to props
  (state: IState) => ({ foo: state.foo }),

  // map dispatch to props
  (dispatch: ThunkDispatch<IState, any, AnyAction>, getState: () => IState) => ({
    handleSmth: () => {
      console.log('something happened');
    },
  }),
)(SomeComponent_Unconnected);

export function AnotherComponent() {
  return (
    <SomeComponent> {/* TS error here, see below */}
      <Text>Test</Text>
    </SomeComponent>
  );
}

A basic usage of Redux in a React here, but I got an strange TS error in AnotherComponent :

Type '{ children: (string | Element)[]; }' is not assignable to type '() => IState'.
Type '{ children: (string | Element)[]; }' provides no match for the signature '(): IState'.ts(2322)

Note that this error disappear if I remove the mapDispatchToProps part of the connect function.

Do you know where does this error come from ? Thanks !

CodePudding user response:

From the redux docs: If your mapDispatchToProps function is declared as taking two parameters, it will be called with dispatch as the first parameter and the props passed to the connected component as the second parameter.

It does not have a getState argument as you provided. Your closed the generic type argument for ThunkDispatch too early with >.

  • Related