【问题标题】:Issue with creating a reselect selector that takes a dynamic argument创建采用动态参数的重新选择选择器的问题
【发布时间】:2017-04-18 14:23:34
【问题描述】:

我正在尝试将动态参数传递给重新选择选择器。原因是这个参数实际上是一个预先不知道的角度路由参数。它也不能是状态的一部分。

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

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);

这是我得到的错误:

“数字”类型的参数不能分配给类型参数 '状态'。

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

有人可以帮忙吗?

【问题讨论】:

    标签: reselect


    【解决方案1】:

    我想出了以下解决方案:

    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));
    

    【讨论】:

      【解决方案2】:

      createSelector 可以创建能够接受任意数量的自定义/动态参数的选择器!见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.您得到的错误不是来自您的应用程序,而是来自您的类型检查器(可能是 Typescript)。

      【讨论】:

        猜你喜欢
        • 2018-04-16
        • 2016-10-11
        • 2017-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多