reselect createStructuredSelector 如何在 Typescript 中工作?

How does reselect createStructuredSelector work in Typescript?

我正在尝试了解 reselect 方法 createStructuredSelector 在 Typescript 中的工作原理。我经常看到这种模式:

export interface SomeProps {
   readonly property1: string;
   readonly property2: boolean;
   readonly property3: number;
}

export interface SomeOwnProps {
   readonly property3: number;
}

export const someSelector = createStructuredSelector<
    SomeState,
    SomeOwnProps,
    SomeProps
>({
   property1: property1Selector,
   property2: property2Selector,
   property3: (_, props) => props.property3
});

我不明白尖括号内类型的用途。我认为 SomeState 是 Redux store 状态, SomeOwnProps 是父组件传入的 props, SomeProps 是该组件使用的所有 props。但是 SomeOwnPropsSomeProps 之间有什么区别,为什么你需要两者?为什么不能只使用 SomeProps 因为它还包含 SomeOwnProps 中定义的属性?谢谢!

createStructuredSelector 有两种变体——一种采用组件自己的 props,另一种不采用。如果你想要的 selection 不依赖于道具,那么选择后者更容易。

考虑这个稍微做作的例子:

/**
 * Data source (Redux store or a single reducer).
 */
interface State {
  readonly property1: string;
  readonly property2: boolean;
  readonly property3: number;
}

/**
 * Your component's OwnProps.
 */
interface OwnProps {
  index: 1 | 2 | 3;
}

/**
 * The interface you want to create.
 */
interface DesiredSelection {
  someString: string;
  someNumber: number;
};

当你的select离子依赖道具时:

const mySelector = createStructuredSelector<State, DesiredSelection>({
  someString: state => state.property1,
  someNumber: state => state.property3
});

当你的select离子依赖道具时:

const mySelectorBasedOnProps = createStructuredSelector<State, OwnProps, DesiredSelection>({
  someString: state => state.property1,
  someNumber: (state, props) =>
    (props.index === 1)
      ? 1
      : state.property3
});

需要区分OwnPropsDesiredSelection,因为前者会影响后者。 select 根据组件从其父组件接收到的道具,从 Redux 商店的不同部分获取数据是一种常见的模式。

比较现实的例子:

interface State {
  translations: {
    au: 'Hello, mate!',
    uk: 'Welcome, old chap!'
  }
}

interface OwnProps {
  country: 'au' | 'uk';
}

interface ConnectedProps {
  message: string
};

/**
 * These are all props your component will receive.
 */
type Props = OwnProps & ConnectedProps;

const getMessage = createStructuredSelector<State, OwnProps, ConnectedProps>({
  message: (state, props) => state.translations[props.country]
});