重新选择createStructuredSelector在Typescript中如何工作?

d0n*_*tz1 6 typescript reactjs react-native redux reselect

我试图了解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
});
Run Code Online (Sandbox Code Playgroud)

我不明白尖括号内的类型的目的。我认为这SomeState是Redux存储状态,SomeOwnProps是父组件传递SomeProps的道具,也是该组件使用的所有道具。但是SomeOwnPropsSomeProps和之间有什么区别?为什么同时需要两者?您为什么不能只使用SomeProps它,因为它还包含中定义的属性SomeOwnProps?谢谢!

Kar*_*ski 8

createStructuredSelector有两种变体-一种采用组件自己的道具,第二种不采用。如果您所需的选择不依赖于道具,则使用后者会更容易。

考虑下面这个人为设计的例子:

/**
 * 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;
};
Run Code Online (Sandbox Code Playgroud)

当您的选择依赖道具时:

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

当您的选择确实取决于道具时:

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

需要区分OwnProps和之间,DesiredSelection因为前者会影响后者。根据组件从其父级收到的道具从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]
});
Run Code Online (Sandbox Code Playgroud)