如何编写处理嵌套状态的几个级别的redux选择器?

问题描述 投票:1回答:2

我希望我的容器组件尽可能地重复使用。为了实现这一点,我想编写可重用的选择器以在mapStateToProps函数中使用它。我知道这个函数可以接受当前组件的props,所以我可以将动态状态键传递给我的选择器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没有传递给组件的道具 - 那么表现正常并寻找第一级状态形状。

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

reactjs redux state derived
2个回答
1
投票

您可以递归重用选择器:

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

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

0
投票

谢谢@iofjuupasli,这是一个很好的解决方案。另外,根据discord redux社区的同意,编写两个选择器会更好。然后为避免代码重复,请写下以下内容:

const SomeComponent = () => {};

const WithSomeDataSource = connect(doOneThingHere)(SomeComponent);
const WithAnotherDataSource = connect(doSomethingElseHere)(SomeComponent);
© www.soinside.com 2019 - 2024. All rights reserved.