【问题标题】:How to write redux selector that handle several levels of nested state?如何编写处理多级嵌套状态的 redux 选择器?
【发布时间】:2019-04-05 08:50:39
【问题描述】:

我希望我的容器组件尽可能地可重用。为此,我想编写可重用的选择器以在 mapStateToProps 函数中使用它。我知道这个函数可以接受当前组件的道具,所以我可以将动态状态键传递给我的选择器getAllEntities。问题出现了,当我想从我的选择器中获得第一级状态,但在其他地方 - 获得一些嵌套状态。

状态形态演示:

{
  items: { byId: { ... }, allIds: { ... } }
  comparison: {
    otherItems: { byId: { ... }, allIds: { ... } }
    // and so on
  }
}

选择器演示:

getAllEntities = (state) => state.allIds.map(id => state.byId[id]);

我在组件的mapStateToProps 函数中使用它:

return { items: getAllEntities(state[ownProps.stateKey]) }

我的方法的问题在于(通过保持该组件的可重用性)我似乎只能访问第一级状态。所以我不能将道具传递给我的组件,它会明白它应该寻找state.comparison.otherItems - 观看上面的状态形状演示。

我尝试了类似的方法:

getAllEntities = (state, key1) => {
  if (has(state, key1) {
    return state[key1].allIds.map(id => state[key1].byId[id]);
  }

  return state.allIds.map(id => state.byId[id]);
} 

所以如果我通过key1 字符串 - 它应该看起来更深的状态。如果 key1 没有传递给组件的 props - 然后正常运行并查找第一级状态形状。

我什至不知道这是否是正确的方法......有人可以帮助我吗?

【问题讨论】:

  • 您是否需要一个选择器来处理这两种情况,带键和不带键?也许你可以做两个选择器,一个用于根状态,一个用于键状态。如果不是 - 你的方法在我看来还不错
  • 嗨@iofjuupasli!我认为只有一个选择器是保持我的组件可重用的必要条件。否则我最终会制作多个外观和工作相同的组件 - 它们之间的唯一区别是 mapStateToProps 函数 - 我使用的选择器......

标签: reactjs redux state derived


【解决方案1】:

你可以递归复用选择器:

getAllEntities = (state, key1) => {
  if (has(state, key1) {
    return getAllEntities(state[key1])
  }

  return state.allIds.map(id => state.byId[id]);
} 

【讨论】:

    【解决方案2】:

    感谢@iofjuupasli,这是一个不错的解决方案。此外,正如 discord redux 社区所同意的,最好编写两个选择器。然后为避免大量代码重复,请编写如下内容:

    const SomeComponent = () => {};
    
    const WithSomeDataSource = connect(doOneThingHere)(SomeComponent);
    const WithAnotherDataSource = connect(doSomethingElseHere)(SomeComponent);
    

    【讨论】:

      猜你喜欢
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2017-09-18
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多