【问题标题】:What is the best implementation for accessing single Redux's store in deeper container component?在更深的容器组件中访问单个 Redux 存储的最佳实现是什么?
【发布时间】:2016-05-27 17:24:48
【问题描述】:

通过定义 mapStateToProps 的 connect() 函数创建容器组件,可以访问整个树状态的状态 (store.getState())。

比如我已经合并了状态树:

{
  loaded: true,
  threads: [
    {
      id: 1,
      title: "Thread 1",
      messages: [
        { 
          id: 1, 
          text: "Message 1"
        }        
      ]
    },
    {
      id: 1,
      title: "Thread 2",
      messages: [
        { 
          id: 2, 
          text: "Message 2"
        },
        { 
          id: 3, 
          text: "Message 3"
        }  
      ]
    }   
  ]
}

我应该如何访问给定线程的特定消息?

const mapStateToProps = (state) => {
  return {
    messages: getMessagesByThread(state.threads, <threadId>)
  }
}

在这种情况下,假设我不想在存储状态树 (store.getState().activeThreadId) 中有“activeThreadId”参数。

提供 threadId 的最佳其他可能性是什么?

【问题讨论】:

    标签: javascript reactjs redux flux


    【解决方案1】:

    如果您有 threadId 作为组件上的道具,您可以通过 ownProps 参数传递它:

    const mapStateToProps = (state, ownProps) => {
      return {
        messages: getMessagesByThread(state.threads, ownProps.threadId)
      }
    }
    

    这是我认为最好的方式。

    【讨论】:

    • 好的,但是深入了解状态树将迫使我提供更多标识符(每个节点的键)来访问较低级别的特定对象。
    • 是的,但是如果您需要在组件中进行特定的按摩,您可以简单地从 messages 属性中选择它?我的意思是,如果您想从一个线程访问一条消息,您无论如何都需要了解完整路径?
    • 是的,也许我不应该——现在就知道了。我的减速器组合应该更简单吗?无论如何,组合reducers 使状态树变得更加复杂是很常见的。
    • 是的,保持状态树平坦,使 reducer 中的处理更加简单。如果您将消息保留在线程旁边并引用消息,则更容易。我建议您阅读此答案:stackoverflow.com/questions/32135779/…
    猜你喜欢
    • 2016-11-22
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多