创建采用动态参数的重新选择选择器的问题

Issue with creating a reselect selector that takes a dynamic argument

我正在尝试将动态参数传递给重新选择选择器。之所以会这样,是因为这个参数其实是一个事先不知道的angular路由参数。它也不能是国家的一部分。

下面是传递路由参数的订阅组件的相关代码:

this.store.select(fromRoot.getMessagesWithOtherUserAccount(this.route.params['otherId']))
      .subscribe(messages => this.messagesWithOtherUserAccount = messages);

这里是选择器的代码:

const getMessagesState = (state: State) => state.message.messages;

//See error below... How can I pass my otherId argument here??
const messagesWithOtherUserAccount = createSelector(getMessagesState, messagesWithCounterParty);

export const getMessagesWithOtherUserAccount = (otherId: number) => messagesWithOtherUserAccount(otherId);

....
export const messagesWithCounterParty = (messages: Message[]) => (otherId: number) => withOtherUserAccount(otherId, messages);

这是我得到的错误:

Argument of type 'number' is not assignable to parameter of type 'State'.

我想将 otherId 参数传递给 messagesWithOtherUserAccount createSelector,但我不确定如何...

有人可以帮忙吗?

我想出了以下解决方案:

this.store.select(fromRoot.getMessagesWithCounterParty(this.route.snapshot.params['otherId']))
  .subscribe(messages => this.messagesWithOtherUserAccount = messages);

export const getMessagesWithCounterParty = (otherId: number) => createSelector(getMessagesState, (messages: Message[]) => withOtherUserAccount(otherId, messages));

createSelector 可以创建能够接受任意数量 custom/dynamic 参数的选择器!参见 createSelector API

在您的情况下,实现结果的伪代码可能是:

// ...

export const getMessagesWithCounterParty = createSelector(
    getMessagesState,               // Accepts the state as 1st argument
    (otherId: number) => otherId,   // Accepts an Id as 2nd argument

    // Result function
    (messages: Message[], otherId: number) => withOtherUserAccount(messages, otherId),
);

// Later in your application:
getMessagesWithCounterParty(yourState, 42);

PS.The 你得到的错误不是来自你的应用程序,而是来自你的类型检查器(可能是 Typescript)。